blob: e26ddd2cbb4c4fe1984c7cd53968008d53acce20 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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
local divisor = 1
for _, monkey in pairs(monkeys) do
divisor = divisor * monkey.test
end
for round = 1,10000 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 = worry % divisor
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)
|