adventofcode-2021/day24/part1.lua

51 lines
1.6 KiB
Lua
Executable File

#!/usr/bin/env luajit
require("utils")
local blocks = {}
local current = nil
local f = io.open(arg[3])
local line = f:read("*l")
while line do
local inst, a1, a2 = unpack(split(line, " "))
if inst == "inp" then
if current ~= nil then
current = string.format("return function(w, x, y, z, input)\n%s\nreturn w, x, y, z\nend", current)
table.insert(blocks, assert(loadstring(current))())
end
current = a1.." = input"
elseif inst == "add" then
current = string.format("%s\n%s = %s + %s", current, a1, a1, a2)
elseif inst == "mul" then
current = string.format("%s\n%s = %s * %s", current, a1, a1, a2)
elseif inst == "div" then
current = string.format("%s\nif %s == 0 then return end\n%s = math.modf(%s / %s)", current, a2, a1, a1, a2)
elseif inst == "mod" then
current = string.format("%s\nif %s < 0 or %s <= 0 then return end\n%s = %s %% %s", current, a1, a2, a1, a1, a2)
elseif inst == "eql" then
current = string.format("%s\nif %s == %s then %s = 1 else %s = 0 end", current, a1, a2, a1, a1)
end
line = f:read("*l")
end
if current ~= nil then
current = string.format("return function(w, x, y, z, input)\n%s\nreturn w, x, y, z\nend", current)
table.insert(blocks, assert(loadstring(current))())
end
local function backtrack(i, w, x, y, z, output)
if i > #blocks then
if z == 0 then
print(string.format("%d", output))
os.exit()
end
else
if i < 7 then print(output) end
for n = 9, 1, -1 do
local w0, x0, y0, z0 = blocks[i](w, x, y, z, n)
if w0 then
backtrack(i + 1, w0, x0, y0, z0, output * 10 + n)
end
end
end
end
backtrack(1, 0, 0, 0, 0, 0)