-
-
Save NobukazuHanada/958d9ca95576834f8a0b 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
require "./rpn" | |
describe "rpn" do | |
it "" do | |
expect(expr(4).("+").(3).("*").(2).("-").(1).("=")). | |
to eq(->(){ | |
comp1 = 3 * 2; | |
comp2 = 3 + comp1; | |
comp3 = comp2 - 1; | |
return comp3 }.call) | |
end | |
end |
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
def expr(e, stack=[], rpn=[]) | |
case e | |
when "=" | |
rpn += stack.reverse | |
return rpn.inject([]) do |arr, token| | |
case token.to_s | |
when /[-+*\/]/ then arr << arr.pop(2).inject($&) | |
when /\d+/ then arr << $&.to_f | |
end | |
end.shift | |
when /[\-+*\/]/ | |
case e | |
when /[*\/]/ then stack << e | |
else rpn += stack.reverse && stack = [e] | |
end | |
else rpn << e | |
end | |
->(e){expr(e, stack, rpn)} | |
end | |
puts expr(4).("+").(3).("*").(2).("-").(1).("=") | |
puts expr(1).("*").(2).("+").(6).("/").(3).("=") | |
puts expr(1).("+").(2).("+").(6).("/").(3).("=") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment