Skip to content

Instantly share code, notes, and snippets.

@ryanhburbank
Created July 2, 2013 15:11
Show Gist options
  • Save ryanhburbank/5910131 to your computer and use it in GitHub Desktop.
Save ryanhburbank/5910131 to your computer and use it in GitHub Desktop.
Reverse Polish Calculator first implementation
#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
#70 10 4 + 5 * - == 70 -(14 *5) == 0
class RPNCalculator
def evaluate(x)
array = x.split(" ")
array.map! do |a|
if a == "+" || a == "-" || a == "*"
a
else
a = a.to_i
end
end
stack = []
operation = 0
array.each_index do |var|
if array[var].class == Fixnum
stack << array[var]
else
if array[var] == "*"
operation = stack[-1] * stack[-2]
stack.pop(2)
stack.push(operation)
elsif array[var] == "+"
operation = stack[-1] + stack[-2]
stack.pop(2)
stack.push(operation)
else
operation = stack[-2] - stack[-1]
stack.pop(2)
stack.push(operation)
end
end
end
return stack[0]
end
end
calc = RPNCalculator.new
puts calc.evaluate('70 10 4 + 5 * -')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment