Created
June 7, 2018 20:11
-
-
Save FrancoB411/1e4b32b2f17df603bdc56397bd3b9096 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Calculator | |
def parse input | |
input.split(" ") | |
end | |
def order_of_operations | |
["*", "/", "+", "-"] | |
end | |
def calculate input | |
inp = parse input | |
while inp.length > 1 do | |
order_of_operations.each do | op | | |
i = inp.find_index(op) | |
if i | |
prev = inp[i-1].to_f | |
nex = inp[i+1].to_f | |
result = operate(prev, op, nex) | |
inp.slice!((i-1)..(i+1)) | |
inp[i-1] = result | |
end | |
end | |
end | |
inp[0] | |
end | |
def operate(prev, op, nex) | |
case op | |
when "*" | |
prev * nex | |
when "/" | |
prev / nex | |
when "+" | |
prev + nex | |
when "-" | |
prev - nex | |
else | |
raise | |
end | |
end | |
end | |
input = '7 - 2 + 3 / 4 * 5' | |
expected = (7 - (2 + (3 / (4 * 5.to_f)))) | |
actual = Calculator.new.calculate(input) | |
puts actual | |
puts (expected == actual) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment