local monkeys = {} for line in io.lines() do if line:match("^Monkey") then local id = line:match("Monkey (%d+)") table.insert(monkeys,{items={},inspected= 0, id=id}) elseif line:match("Starting items:") then for item in line:gmatch("(%d+)") do table.insert(monkeys[#monkeys].items,tonumber(item)) end elseif line:match("Operation:") then op, val = line:match("new = old (.) (%S+)") monkeys[#monkeys].op = op monkeys[#monkeys].val = val elseif line:match("Test:") then monkeys[#monkeys].test = tonumber(line:match("Test: divisible by (%d+)")) elseif line:match("If true:") then monkeys[#monkeys].t = tonumber(line:match("throw to monkey (%d+)")) + 1 elseif line:match("If false:") then monkeys[#monkeys].f = tonumber(line:match("throw to monkey (%d+)")) + 1 end end for round = 1,20 do for turn, monkey in ipairs(monkeys) do monkey.inspected = monkey.inspected + #monkey.items for _,item in ipairs(monkey.items) do local worry = item if monkey.op == "+" and monkey.val == "old" then worry = worry * 2 elseif monkey.op == "*" and monkey.val == "old" then worry = worry * worry elseif monkey.op == "+" and tonumber(monkey.val) then worry = worry + tonumber(monkey.val) elseif monkey.op == "*" and tonumber(monkey.val) then worry = worry * tonumber(monkey.val) end local newworry = math.floor(worry / 3) if newworry % monkey.test == 0 then table.insert(monkeys[monkey.t].items,newworry) else table.insert(monkeys[monkey.f].items,newworry) end end monkey.items = {} end end table.sort(monkeys, function(a,b) return a.inspected > b.inspected end) print(monkeys[1].inspected * monkeys[2].inspected)