Last active
May 11, 2016 05:39
-
-
Save shaselton/f643d77e307344f5149eece7e0fcfc8f 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
# Create a simple calculator that given a string of operators (+ - * and /) | |
# and numbers separated by spaces returns the value of that expression | |
# Example: | |
# Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") # => 7 | |
# Remember about the order of operations! Multiplications and divisions have | |
# a higher priority and should be performed left-to-right. Additions and | |
# subtractions have a lower priority and should also be performed left-to-right. | |
class Calculator | |
def initialize | |
@priority_operators = ['/', '*'] | |
end | |
def evaluate(equation) | |
operands = equation.split(' ').select.with_index {|v, i| i.even?}.map(&:to_i) | |
operators = equation.split(' ').select.with_index {|v, i| i.odd?} | |
operation(operands, operators) | |
end | |
def operation(operands, operators) | |
return operands.pop if operands.size == 1 | |
operators.each_with_index do |val, index| | |
if @priority_operators.include?(val) | |
operands.insert(index, calculation(operands.slice!(index, 2), operators.slice!(index))) | |
return operation(operands, operators) | |
end | |
end | |
operands.unshift(calculation(operands.shift(2), operators.shift)) | |
operation(operands, operators) | |
end | |
def calculation(operands, operator) | |
operands[0].send(operator, operands[1]) | |
end | |
end | |
puts Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment