-
-
Save anonymous/29f5a52fa6c0aa5d7549c7fdae19e560 to your computer and use it in GitHub Desktop.
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
it "evaluates a string" do | |
expect(calculator.evaluate("1 2 3 * +")).to eq( | |
((2 * 3) + 1) | |
) | |
expect(calculator.evaluate("4 5 -")).to eq( | |
(4 - 5) | |
) | |
expect(calculator.evaluate("2 3 /")).to eq( | |
(2.0 / 3.0) | |
) | |
expect(calculator.evaluate("1 2 3 * + 4 5 - /")).to eq( | |
(1.0 + (2 * 3)) / (4 - 5) | |
) | |
end | |
end | |
class RPNCalculator | |
def initialize | |
@logic = [] | |
end | |
def push(to_push) | |
@logic << to_push | |
end | |
def plus | |
if @logic.length < 2 | |
raise "calculator is empty" | |
else | |
@logic.push(@logic.pop + @logic.pop) | |
end | |
end | |
def minus | |
if @logic.length < 2 | |
raise "calculator is empty" | |
else | |
fnum = @logic.pop | |
@logic.push(@logic.pop - fnum) | |
end | |
end | |
def value | |
@logic.last | |
end | |
def divide | |
if @logic.length < 2 | |
raise "calculator is empty" | |
else | |
fnum = @logic.pop | |
@logic.push(@logic.pop.to_f / fnum.to_f) | |
end | |
end | |
def times | |
if @logic.length < 2 | |
raise "calculator is empty" | |
else | |
@logic.push(@logic.pop * @logic.pop) | |
end | |
end | |
def tokens(string) | |
val = string.split | |
val.map! do |x| | |
if x == "-" | |
x = :- | |
elsif x == "+" | |
x = :+ | |
elsif x == "/" | |
x = :/ | |
elsif x == "*" | |
x = :* | |
else | |
x = x.to_i | |
end | |
end | |
val | |
end | |
#1 2 3 * + | |
def evaluate(value) | |
tokens = tokens(value) | |
symbols = [] | |
numbers = [] | |
num = nil | |
tokens.each do |x| | |
if [:-, :+, :/, :*].include?(x) | |
symbols << x | |
else | |
numbers << x | |
end | |
end | |
while(numbers.length > 0) | |
#If this is the first pass, we need to take 2 values instead of 1. | |
num = numbers.pop | |
if(numbers.length + 1 + symbols.length == tokens.length) | |
push(numbers.pop) | |
push(num) | |
else | |
push(num) | |
end | |
sign = symbols.shift | |
if(sign == :+) | |
plus | |
elsif(sign == :-) | |
minus | |
elsif(sign == :/) | |
divide | |
else | |
times | |
end | |
end | |
self.value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment