Skip to content

Instantly share code, notes, and snippets.

@mhriess
Created August 24, 2012 16:15
Show Gist options
  • Save mhriess/3452431 to your computer and use it in GitHub Desktop.
Save mhriess/3452431 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
Create an RPNCalculator class which can evaluate expressions
written in Reverse Polish notation.
It should have an evaluate instance method which takes as its
input a valid RPN expression and returns its evaluation. Your
calculator only needs to handle addition, multiplication, and
subtraction (not division).
Operators and numbers should be separated by a single space.
For example,
calc = RPNCalculator.new
calc.evaluate('1 2 +') # => 3
calc.evaluate('2 5 *') # => 10
calc.evaluate('50 20 -') # => 30
# The general rule is that 'A B op' is the same as 'A op B'
# i.e., 5 4 - is 5 - 4.
calc.evaluate('70 10 4 + 5 * -') # => 0
class RPNCalculator
def evaluate(expression)
operators = ["+", "-", "*"]
stack = []
array = expression.split(" ")
array.each do |i|
if operators.include?(i)
second_operand = stack.pop
first_operand = stack.pop
stack.push(first_operand.send(i, second_operand))
else
stack.push(i.to_i)
end
end
stack.pop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment