Skip to content

Instantly share code, notes, and snippets.

@FrancoB411
Created June 7, 2018 20:42
Show Gist options
  • Save FrancoB411/5df6aaad728c0cfd6ae761e7ae0e2498 to your computer and use it in GitHub Desktop.
Save FrancoB411/5df6aaad728c0cfd6ae761e7ae0e2498 to your computer and use it in GitHub Desktop.
class Calculator
def parse input
input.split(" ")
end
def order_of_operations
["*", "/", "+", "-"]
end
def calculate input
recursive_calc(parse input)
end
def recursive_calc(input)
return input[0] if input.length == 1
order_of_operations.each do | op |
i = input.find_index(op)
if i
prev = input[i-1].to_f
nex = input[i+1].to_f
result = operate(prev, op, nex)
input.slice!((i-1)..(i+1))
input[i-1] = result
return recursive_calc(input)
end
end
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