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

89 lines
2.2 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
monkey.sign = sign
monkey.num = num
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
local divisors = {}
local period = 1
for _, monkey in ipairs(monkeys) do
table.insert( divisors, monkey.divisor )
period = period * monkey.divisor
end
for round = 1,10000 do
print("round", round)
for i, monkey in ipairs(monkeys) do
for _, item in ipairs(monkey.q) do
local worry = monkey.f(item)%period
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
--[[
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
print(monkeys[1].count,monkeys[2].count, monkeys[3].count, monkeys[4].count)
table.sort(monkeys, function(a,b) return a.count > b.count end)
local result = monkeys[1].count*monkeys[2].count
print("part 2", result)