Last active
May 27, 2019 09:30
-
-
Save obelisk68/7e0eaf56eb4ff16ac2aa7db28426e287 to your computer and use it in GitHub Desktop.
四則演算のパーサー(Ruby)
This file contains hidden or 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 parse(text) | |
splited = text.scan(/[0-9\.]+|\+|\-|\*|\/|\(|\)|=/) | |
output = [] | |
stack = [] | |
a = nil | |
until (token = splited.shift) == "=" | |
case token | |
when "(" then stack << token | |
when ")" | |
output << a until (a = stack.pop) == "(" | |
when "*", "/" | |
loop do | |
a = stack.last | |
break unless %w(* /).include?(a) | |
output << stack.pop | |
end | |
stack << token | |
when "+", "-" | |
loop do | |
a = stack.last | |
break unless %w(+ - * /).include?(a) | |
output << stack.pop | |
end | |
stack << token | |
else | |
output << token | |
end | |
end | |
output << a while (a = stack.pop) | |
return output | |
end | |
def calculate(parsed) | |
stack = [] | |
while (x = parsed.shift) | |
if %w(+ - * /).include?(x) | |
a, b = stack.pop, stack.pop | |
stack << eval("#{b} #{x} #{a}") | |
else | |
stack << x | |
end | |
end | |
stack.first | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment