Last active
August 29, 2015 14:23
-
-
Save jakenotjacob/e6d6239a4b1d79f3c87f to your computer and use it in GitHub Desktop.
Beginning of RPN calc.
This file contains hidden or 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
#!/usr/bin/env ruby | |
OPERATORS = { | |
"x": :*, | |
"/": :fdiv, | |
"+": :+, | |
"-": :- | |
} | |
def is_value?(token) | |
true ^ OPERATORS[token.to_sym] | |
end | |
while input = gets.chomp.split | |
stack = [] | |
input.each do |token| | |
if is_value? token | |
stack << token.to_i | |
else | |
left, right = stack.pop(2) | |
val = left.send OPERATORS[token.to_sym], right | |
stack << val | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment