-
-
Save xcobar/296851bc2095fe8bd81af5bf4d8c5147 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The standard C library provides an important, low level function that many other | |
# programming languages and tools rely on called `atof`. | |
# The goal of atof is simple: to convert a correctly formatted string to a double | |
# precision floating point number (also know as 64bit float, double, etc). | |
# For example: | |
# ie atof("574.32") => 574.32, atof("23") => 23.0, etc | |
# | |
# Lets implement this primitive parsing function ourselves! | |
# Constraints: | |
# You may use string library functions that return strings however you like. | |
# For instance, you may use regexes, split, etc. | |
# You may only pass single character strings into library functions that return numbers | |
# For instance, you can only pass a single digit '9' into parseInt or parseFloat functions, but not '9.9', or '99'. You need to combine the results and parse the remaining input! | |
# You may pass multi character strings to any utility function you write yourself. | |
# Feel free to still create helper functions to divide the problem into steps. | |
# Non Concerns: | |
# Assume all inputs are validly formatted. Do not worry about handling invalid | |
# input strings. | |
# | |
# We will implement the full atof in small discrete steps, each focusing on a | |
# specific domain of valid inputs and tests to pass. Please demonstrate passing | |
# all tests before proceeding to further atof features. | |
# For example, pass all the positive integer tests before continuing on to handle | |
# negative integers, etc. | |
# | |
# Do not stress if you don't complete the whole problem! We'll work as through as | |
# much of the problem as we have time to solve. | |
def atof(string) | |
return nil | |
end | |
def verify_input(string, expected) | |
actual = atof(string) | |
if actual != expected | |
warn "Expected #{expected} but got #{actual}" | |
return | |
end | |
puts "passed" | |
end | |
# start with integers | |
verify_input("5", 5.0) | |
verify_input("50", 50.0) | |
verify_input("847600", 847600.0) | |
verify_input("0", 0.0) | |
verify_input("2", 2.0) | |
verify_input("139", 139.0) | |
# # negatives | |
verify_input("-23", -23.0) | |
verify_input("-2005", -2005.0) | |
verify_input("-23194", -23194.0) | |
# # floats | |
verify_input("-0.020350", -0.02035) | |
verify_input("125.4", 125.4) | |
verify_input("78493.119002", 78493.119002) | |
# # scientific notation | |
verify_input("254.03E6", 254030000) | |
verify_input("-0.31E-150", -3.1e-151) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment