Created
December 6, 2018 09:29
-
-
Save ser1zw/98b0512106fb24a3a84ec255ce0d3a07 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 'set' | |
class RPN | |
def initialize(exp) | |
@exp = exp.split(/\s+/) | |
@stack = [] | |
@operators = Set['+', '-', '*', '/', '%'].freeze | |
end | |
def eval | |
while v = @exp.shift | |
if @operators.include? v | |
n2, n1 = @stack.pop, @stack.pop | |
@stack << n1.send(v.to_sym, n2) | |
else | |
@stack << v.to_i | |
end | |
end | |
@stack.last | |
end | |
end | |
DATA.read.lines.map(&:chomp).each { |exp| | |
puts "(#{exp}) = #{RPN.new(exp).eval}" | |
} | |
__END__ | |
3 4 + | |
3 4 + 1 2 - * | |
1 5 + 2 3 + * |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment