advent-of-code/12022/11/11.lua

78 lines
1.9 KiB
Lua

io.input("test")
io.input("input")
local monkeys = {}
local lineIndex = 1
local monkey
-- parsing
for line in io.lines() do
if line=="" then
lineIndex = 1
goto continue
end
if lineIndex == 1 then
local newmonkey = { q = {}, targets ={}, count=0 }
monkey = newmonkey
table.insert(monkeys, newmonkey)
elseif lineIndex == 2 then -- starting items
local q = {}
for item in string.gmatch(line, "%d+") do
table.insert( q, tonumber(item) )
end
monkey.q = q
elseif lineIndex == 3 then -- operation
local sign, value = string.match(line, "([+*]) (.+)$")
local num = tonumber(value)
local f
if sign == "*" then
f = function (x) local v = num or x
return x*v
end
else
f = function (x) local v = num or x
return x+v
end
end
monkey.f = f
elseif lineIndex == 4 then -- divisor
monkey.divisor = tonumber(string.match(line, "%d+$"))
elseif lineIndex == 5 then -- targets
monkey.targets[true] = tonumber(string.match(line, "%d+$"))+1
elseif lineIndex == 6 then -- targets
monkey.targets[false] = tonumber(string.match(line, "%d+$"))+1
end
lineIndex = lineIndex + 1
::continue::
end
for round = 1,20 do
for i, monkey in ipairs(monkeys) do
for _, item in ipairs(monkey.q) do
local worry = monkey.f(item)//3
local divisible = worry%monkey.divisor==0
local target = monkey.targets[divisible]
table.insert( monkeys[target].q, worry )
monkey.count = monkey.count + 1
end
monkey.q = {} -- empty queue
end
-- for debugging
--[[
print("round", round)
for i, monkey in ipairs(monkeys) do
print("monkey", i-1, monkey.count)
local oq =""
for _, item in ipairs(monkey.q) do
oq = oq .. tostring(item) .. ","
end
print(oq)
end
]]
end
table.sort(monkeys, function(a,b) return a.count > b.count end)
print("part 1", monkeys[1].count*monkeys[2].count)