Skip to content

Instantly share code, notes, and snippets.

@kayline
Created March 21, 2013 03:52
Show Gist options
  • Save kayline/5210557 to your computer and use it in GitHub Desktop.
Save kayline/5210557 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator. Can do recursively?
class RPNCalculator
def evaluate(input)
puts "BEGIN NEW CALC"
stack = []
puts "Initial input is #{input}"
until input == ""
item = input.match(/\A\S*/)
puts "Current item is #{item}"
item_string = item.to_s
test = item_string.match(/\d/)
if test
num_item = item_string.to_f
stack.push(num_item)
puts "Added #{item} to the stack"
elsif item_string == '+'
b = stack.pop
a = stack.pop
sum = a + b
stack.push(sum)
elsif item_string == '-'
b = stack.pop
a = stack.pop
diff = a - b
stack.push(diff)
elsif item_string == '*'
b = stack.pop
a = stack.pop
prod = a * b
stack.push(prod)
else
puts "WARNING!!"
return "Error: unknown input #{item} Remaining input is #{input}"
end
puts "Made it through the loop"
size = item_string.length
chops = size + 1
chops.times do
input = input.reverse.chop.reverse
end
puts "Remaining input is #{input}"
end
puts "Exited the loop"
puts stack.inspect
puts "The result is #{stack[0]}"
return stack[0]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment