Skip to content

Instantly share code, notes, and snippets.

@mattdvhope
Last active December 20, 2015 23:58
Show Gist options
  • Save mattdvhope/6216031 to your computer and use it in GitHub Desktop.
Save mattdvhope/6216031 to your computer and use it in GitHub Desktop.
Reverse Polish notation calculator
class RPNCalculator
def evaluate(values_and_operator)
@array = (values_and_operator).split(' ')
if @array.length == 1
return @array.pop.to_i
end
while true
@array.each_with_index do |element, i|
if element == "+"
after_op = @array.drop(i + 1)
sum = (@array[i - 2]).to_i + (@array[i - 1]).to_i
length_before_op = @array.length - (after_op.length + 3)
before_op = @array.take(length_before_op)
@array = [] << before_op << sum << after_op
@array = @array.flatten!
return sum if @array.length == 1
break
elsif element == "*"
after_op = @array.drop(i + 1)
prod = (@array[i - 2]).to_i * (@array[i - 1]).to_i
length_before_op = @array.length - (after_op.length + 3)
before_op = @array.take(length_before_op)
@array = [] << before_op << prod << after_op
@array = @array.flatten!
return prod if @array.length == 1
break
elsif element == "-"
after_op = @array.drop(i + 1)
diff = (@array[i - 2]).to_i - (@array[i - 1]).to_i
length_before_op = @array.length - (after_op.length + 3)
before_op = @array.take(length_before_op)
@array = [] << before_op << diff << after_op
@array = @array.flatten!
return diff if @array.length == 1
break
end # end for if
end # end for do
end # end for while
end # end for def
end
@mattdvhope
Copy link
Author

just got it! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment