Last active
December 20, 2015 23:58
-
-
Save mattdvhope/6216031 to your computer and use it in GitHub Desktop.
Reverse Polish notation calculator
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
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 |
If it works and it passed all the specs, why don't you just look at how everyone else did it? I always learn something when I see how others have completed the exercise.
Hi Ryan, I got it to work with my computer, but according to Socrates, it won't work with '0' and '-1'. Therefore I can't view other folks' ex's yet. It's getting closer though. Jake helped me with the single integers. Thx.
just got it! Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I realize that I'm violating DRY here, but I can't find a way to avoid repeating after the "if" or "elsif".
It works with whatever I can throw at it, including negative integers.
It doesn't violate any of the Socrates Specs, as far as I can tell.