Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Calculator
- def tokenize(input)
- input.split.map do |token|
- Float(token) rescue token
- end
- end
- # operation(3.0, "+", 4.0) returns 7.0 etc.
- def operation(a, op, b)
- raise "Expected A and B to be numbers" unless a.is_a?(Float) and b.is_a?(Float)
- case op
- when "+"
- a + b
- when "-"
- a - b
- when "*"
- a * b
- when "/"
- a / b
- else
- raise "Unknown operator #{op}"
- end
- end
- # turn [..., 3, "+", 4, ...]
- # into [..., 7, ...]
- # where index_op points at operator
- def replace_expr_with_result(tokens, index_op)
- a, op, b = tokens[index_op-1..index_op+1]
- result = operation(a, op, b)
- tokens[index_op-1..index_op+1] = [result]
- end
- def calculate(input)
- tokens = tokenize(input)
- # First do all * and /
- loop do
- index_op = tokens.index do |token|
- token == "*" or token == "/"
- end
- break unless index_op
- replace_expr_with_result(tokens, index_op)
- end
- # Then do all + and -
- loop do
- index_op = tokens.index do |token|
- token == "+" or token == "-"
- end
- break unless index_op
- replace_expr_with_result(tokens, index_op)
- end
- raise "Extra stuff after all operations: #{tokens.inspect}" if tokens.size > 1
- tokens[0]
- end
- end
- input = "2 + 3 * 4 - 8 / 4 * 3 - 6 - 8"
- result = Calculator.new.calculate(input)
- expected = eval(input)
- p [result, expected]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement