|
|
@ -1,32 +1,58 @@
|
|
|
|
require "strscan"
|
|
|
|
require "strscan"
|
|
|
|
|
|
|
|
|
|
|
|
def evaluate(input)
|
|
|
|
# def evaluate(input)
|
|
|
|
while input.include?(?()
|
|
|
|
# while input.include?(?()
|
|
|
|
input = input.gsub(/\((?~[()])+\)/) {|m| evaluate(m[1..-2]) }
|
|
|
|
# input = input.gsub(/\((?~[()])+\)/) {|m| evaluate(m[1..-2]) }
|
|
|
|
end
|
|
|
|
# end
|
|
|
|
|
|
|
|
|
|
|
|
# ss = StringScanner.new(input)
|
|
|
|
# # part one
|
|
|
|
# n = ss.scan(/\d+/).to_i
|
|
|
|
# # ss = StringScanner.new(input)
|
|
|
|
# until ss.eos?
|
|
|
|
# # n = ss.scan(/\d+/).to_i
|
|
|
|
# case
|
|
|
|
# # until ss.eos?
|
|
|
|
# when ss.scan(/\s*\+\s*(\d+)/)
|
|
|
|
# # case
|
|
|
|
# n += ss.captures[0].to_i
|
|
|
|
# # when ss.scan(/\s*\+\s*(\d+)/)
|
|
|
|
# when ss.scan(/\s*\*\s*(\d+)/)
|
|
|
|
# # n += ss.captures[0].to_i
|
|
|
|
# n *= ss.captures[0].to_i
|
|
|
|
# # when ss.scan(/\s*\*\s*(\d+)/)
|
|
|
|
# else
|
|
|
|
# # n *= ss.captures[0].to_i
|
|
|
|
# fail
|
|
|
|
# # else
|
|
|
|
# end
|
|
|
|
# # fail
|
|
|
|
# end
|
|
|
|
# # end
|
|
|
|
# n
|
|
|
|
# # end
|
|
|
|
|
|
|
|
# # n
|
|
|
|
|
|
|
|
|
|
|
|
while input.include?(?+)
|
|
|
|
# while input.include?(?+)
|
|
|
|
input = input.gsub(/\d+\s*\+\s*\d+/) {|m| eval(m) }
|
|
|
|
# input = input.gsub(/\d+\s*\+\s*\d+/) {|m| eval(m) }
|
|
|
|
|
|
|
|
# end
|
|
|
|
|
|
|
|
# while input.include?(?*)
|
|
|
|
|
|
|
|
# input = input.gsub(/\d+\s*\*\s*\d+/) {|m| eval(m) }
|
|
|
|
|
|
|
|
# end
|
|
|
|
|
|
|
|
# input.to_i
|
|
|
|
|
|
|
|
# end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def evaluate(input)
|
|
|
|
|
|
|
|
stack = [->(x) { x }]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ss = StringScanner.new(input)
|
|
|
|
|
|
|
|
until ss.eos?
|
|
|
|
|
|
|
|
ss.scan(/\s*/)
|
|
|
|
|
|
|
|
case
|
|
|
|
|
|
|
|
when n = ss.scan(/\d+/)
|
|
|
|
|
|
|
|
stack << stack.pop[n.to_i]
|
|
|
|
|
|
|
|
when ss.scan(/\+/)
|
|
|
|
|
|
|
|
stack << ->(x) { stack.pop + x }
|
|
|
|
|
|
|
|
when ss.scan(/\*/)
|
|
|
|
|
|
|
|
stack << ->(x) { stack.pop * x }
|
|
|
|
|
|
|
|
when ss.scan(/\(/)
|
|
|
|
|
|
|
|
stack << ->(x) { x }
|
|
|
|
|
|
|
|
when ss.scan(/\)/)
|
|
|
|
|
|
|
|
n = stack.pop
|
|
|
|
|
|
|
|
stack << stack.pop[n]
|
|
|
|
|
|
|
|
else
|
|
|
|
|
|
|
|
fail
|
|
|
|
end
|
|
|
|
end
|
|
|
|
while input.include?(?*)
|
|
|
|
|
|
|
|
input = input.gsub(/\d+\s*\*\s*\d+/) {|m| eval(m) }
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|
|
|
|
input.to_i
|
|
|
|
|
|
|
|
|
|
|
|
stack.pop
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
p ARGF.read.split("\n").map {|line| evaluate(line) }.sum
|
|
|
|
p ARGF.read.split("\n").map {|line| evaluate(line) }.sum
|
|
|
|
|
|
|
|
|
|
|
|