Last active
December 11, 2015 14:29
Reverse Polish Notation
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
def rpn expression | |
stack = [] | |
expression.split(' ').each do |token| | |
stack << if token =~ /\d/ | |
token | |
else | |
[stack.pop, stack.pop].map { |t| t.to_i }.inject do |sum, x| | |
eval "#{x} #{token} #{sum}" | |
end | |
end | |
end | |
stack.last | |
end |
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
require './rpn' | |
describe 'rpn' do | |
it 'should support 1 + 1' do | |
rpn('1 1 +').should eql 2 | |
end | |
it 'should support minus' do | |
rpn('1 2 3 + -').should eql -4 | |
end | |
it 'should support varying orders' do | |
rpn("1 2 + 3 -").should eql 0 | |
end | |
it "should support zeros" do | |
rpn('1 0 +').should eql 1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment