49 lines
1.1 KiB
Lua
49 lines
1.1 KiB
Lua
--io.input("test")
|
|
io.input("input")
|
|
|
|
local m = {}
|
|
for line in io.lines() do
|
|
local pattern = "^(%a+): (.+)$"
|
|
local name, arg = string.match(line, pattern)
|
|
local num = tonumber(arg)
|
|
if num then
|
|
m[name] = function() return num end
|
|
else
|
|
local pattern = "(%a+) ([%+%-%*%/]) (%a+)"
|
|
local a, op, b = string.match(arg, pattern)
|
|
if op == "+" then
|
|
m[name] = function() return m[a]()+m[b]() end
|
|
-- for part 2
|
|
if name == "root" then
|
|
m["root2"] = function() return m[a]()-m[b]() end
|
|
end
|
|
elseif op == "-" then
|
|
m[name] = function() return m[a]()-m[b]() end
|
|
elseif op == "*" then
|
|
m[name] = function() return m[a]()*m[b]() end
|
|
elseif op == "/" then
|
|
m[name] = function() return m[a]()/m[b]() end
|
|
end
|
|
end
|
|
end
|
|
|
|
local result1 = m["root"]()
|
|
print( string.format("part 1: %d", result1) )
|
|
|
|
-- part 2
|
|
local at = 0
|
|
local inc = 10000000000
|
|
repeat
|
|
repeat
|
|
m["humn"] = function() return at end
|
|
dif = m["root2"]()
|
|
at = at + inc
|
|
until dif <= 0
|
|
if dif==0 then break end
|
|
at = at - 10*inc
|
|
inc = inc/10
|
|
until inc < 1
|
|
|
|
local result2 = at - inc
|
|
print( string.format("part 2: %d", result2))
|