Created
October 31, 2012 11:10
-
-
Save jpcaruana/3986486 to your computer and use it in GitHub Desktop.
Reverse Polish notation (ruby)
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
require "test/unit" | |
OPERATIONS = { | |
"+" => lambda { |a, b| a + b }, | |
"-" => lambda { |a, b| a - b }, | |
"*" => lambda { |a, b| a * b }, | |
"/" => lambda { |a, b| a / b } | |
} | |
def eval_polish(expression) | |
elements = expression.split | |
stack = [] | |
elements.each { |element| | |
if OPERATIONS.keys.include? element | |
b = stack.pop | |
a = stack.pop | |
stack.push OPERATIONS[element].call a, b | |
else | |
stack.push element.to_i | |
end | |
} | |
stack.pop | |
end | |
class PolishTest < Test::Unit::TestCase | |
def test_soustraction | |
assert_equal 1, eval_polish('3 2 -') | |
assert_equal 3, eval_polish('5 2 -') | |
end | |
def test_addition | |
assert_equal 5, eval_polish('3 2 +') | |
end | |
def test_addition_2_etages | |
assert_equal 6, eval_polish('3 2 1 + +') | |
end | |
def test_multiplication | |
assert_equal 6, eval_polish('3 2 *') | |
end | |
def test_division | |
assert_equal 2, eval_polish('4 2 /') | |
end | |
def test_acceptance | |
assert_equal 2, eval_polish('4 2 5 * + 1 3 2 * + /') | |
assert_equal 14, eval_polish('5 1 2 + 4 * 3 - +') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same, using functional style :
https://gist.github.com/3976975#file_postfix.rb