Created
July 23, 2013 17:10
-
-
Save fabianuribe/6064174 to your computer and use it in GitHub Desktop.
RPN
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
# Create an RPNCalculator class which can evaluate expressions written in Reverse Polish notation. | |
# It should have an evaluate instance method which takes as its input a valid RPN expression and returns its evaluation. Your calculator only needs to handle addition, multiplication, and subtraction (not division). | |
# Operators and numbers should be separated by a single space. | |
# For example, | |
# calc = RPNCalculator.new | |
# calc.evaluate('1 2 +') # => 3 | |
# calc.evaluate('2 5 *') # => 10 | |
# calc.evaluate('50 20 -') # => 30 | |
# # The general rule is that 'A B op' is the same as 'A op B' | |
# # i.e., 5 4 - is 5 - 4. | |
# calc.evaluate('70 10 4 + 5 * -') # => 0 | |
# 70 - ((10 + 4) * 5 ) | |
# | |
# | |
# Implement an RPN calculator that takes an expression like | |
# 19 2.14 + 4.5 2 4.3 / - * | |
# which is usually expressed as (19 + 2.14) * (4.5 - 2 / 4.3) | |
class RPNCalculator | |
def initialize | |
@array = Array.new | |
@stack = Array.new | |
end | |
def evaluate(string) | |
@array = string.split | |
@array.each do |x| | |
if x.match(/(\d+)/) | |
@stack << x.to_i | |
else | |
case x | |
when '+' | |
@stack << @stack.pop + @stack.pop | |
when '-' | |
@stack << - @stack.pop + @stack.pop | |
when '*' | |
@stack << @stack.pop * @stack.pop | |
end | |
end | |
end | |
return @stack.join.to_i | |
end | |
end | |
calculator = RPNCalculator.new | |
#Test operation :Should print : 0 | |
p calculator.evaluate("70 10 4 + 5 * -") | |
p calculator.evaluate("12 2 3 + *") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment