Skip to content

Instantly share code, notes, and snippets.

/test_first.rb Secret

Last active September 22, 2016 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/29f5a52fa6c0aa5d7549c7fdae19e560 to your computer and use it in GitHub Desktop.
Save anonymous/29f5a52fa6c0aa5d7549c7fdae19e560 to your computer and use it in GitHub Desktop.
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