Created
January 7, 2015 02:15
-
-
Save granolocks/9da1625572a2d3aa2203 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
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 'rspec' | |
| module RPN | |
| def calculate(input="") | |
| do_calculate(input.split(' ').map{|t|t == "#{t.to_i}" ? t.to_i : t.to_sym}) | |
| end | |
| def do_calculate(tokens=[]) | |
| if tokens.length == 3 | |
| x,y,opp = tokens | |
| [:+, :-, :*, :/].include?(opp) ? x.send(opp,y) : "Invalid Input" | |
| elsif tokens.length > 3 | |
| x,y,opp = tokens[0], do_calculate(tokens[1..-2]), tokens[-1] | |
| do_calculate([x,y,opp]) | |
| else | |
| "Invalid Input" | |
| end | |
| end | |
| module_function :calculate, :do_calculate | |
| end | |
| samples = [ | |
| ["", "Invalid Input" ], | |
| ["1 1", "Invalid Input" ], | |
| ["1 1 ?", "Invalid Input" ], | |
| ["1 1 +", 2 ], | |
| ["5 4 -", 1 ], | |
| ["99 100 *", 9900 ], | |
| ["10 2 /", 5 ], | |
| ["6 2 3 + -", 1 ], | |
| ["5 6 2 3 + - *", 5 ] | |
| ] | |
| describe RPN do | |
| samples.each do |sample| | |
| it "interprets '#{sample[0]}' and returns #{sample[1]}" do | |
| expect(RPN.calculate(sample[0])).to eq(sample[1]) | |
| end | |
| end | |
| end | |
| # Below is a sample run of these tests: | |
| # | |
| # $ rspec -fd rpn.rb | |
| # RPN | |
| # interprets '' and returns Invalid Input | |
| # interprets '1 1' and returns Invalid Input | |
| # interprets '1 1 ?' and returns Invalid Input | |
| # interprets '1 1 +' and returns 2 | |
| # interprets '5 4 -' and returns 1 | |
| # interprets '99 100 *' and returns 9900 | |
| # interprets '10 2 /' and returns 5 | |
| # interprets '6 2 3 + -' and returns 1 | |
| # interprets '5 6 2 3 + - *' and returns 5 | |
| # | |
| # Finished in 0.00232 seconds (files took 0.15198 seconds to load) | |
| # 9 examples, 0 failures |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment