Skip to content

Instantly share code, notes, and snippets.

@lilliealbert
Last active December 16, 2015 00:29
Show Gist options
  • Save lilliealbert/5347902 to your computer and use it in GitHub Desktop.
Save lilliealbert/5347902 to your computer and use it in GitHub Desktop.
computers are hard
class RPNCalculator
def evaluate(exp)
exp_array = exp.split(" ").to_a
rpn_array = []
exp_array.each do |i|
if i.match(/\d/) != nil
rpn_array << i.to_i
else
rpn_array << i
end
end
while rpn_array.length > 1
rpn_array.length.times do |index|
operator = rpn_array[index]
case operator
when "+", "-", "*"
case operator
when "+"
result = rpn_array[index-2] + rpn_array[index-1]
when "-"
result = rpn_array[index-2] - rpn_array[index-1]
when "*"
result = rpn_array[index-2] * rpn_array[index-1]
end
rpn_array[rpn_array.index(operator)] = result
rpn_array.delete_at(index-1)
rpn_array.delete_at(index-2)
break
end
end
end
rpn_array[0]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment