Created
March 21, 2013 03:52
-
-
Save kayline/5210557 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator. Can do recursively?
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
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