-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
day_11.py
88 lines (71 loc) · 2.4 KB
/
day_11.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import math
import aoc_helper
from aoc_helper import (
Grid,
PrioQueue,
decode_text,
extract_ints,
frange,
irange,
iter,
list,
map,
range,
tail_call,
)
raw = aoc_helper.fetch(11, 2022)
def parse_one(raw):
_, starting, op, test, true, false = raw.splitlines()
return {
"items": extract_ints(starting),
"op": op.removeprefix(" Operation: "),
"test": extract_ints(test)[0],
"true": extract_ints(true)[0],
"false": extract_ints(false)[0],
}
def parse_raw(raw):
return list(raw.split("\n\n")).mapped(parse_one)
data = parse_raw(raw)
def part_one(data):
data = data.deepcopy()
inspected = [0 for _ in data]
for _ in range(20):
for i, monkey in enumerate(data):
for old in monkey["items"]:
inspected[i] += 1
new = 0
_locals = {"old": old}
exec(monkey["op"], {}, _locals)
new = _locals["new"]
new = new // 3
if new % monkey["test"] == 0:
data[monkey["true"]]["items"].append(new)
else:
data[monkey["false"]]["items"].append(new)
monkey["items"].clear()
return math.prod(sorted(inspected)[-2:])
aoc_helper.lazy_test(day=11, year=2022, parse=parse_raw, solution=part_one)
def part_two(data):
data = data.deepcopy()
inspected = [0 for _ in data]
loop_factor = math.prod(monkey["test"] for monkey in data)
for _ in range(10000):
for i, monkey in enumerate(data):
for old in monkey["items"]:
inspected[i] += 1
new = 0
_locals = {"old": old}
exec(monkey["op"], {}, _locals)
new = _locals["new"]
new = (
new
) % loop_factor # shrink the number without affecting the tests
if new % monkey["test"] == 0:
data[monkey["true"]]["items"].append(new)
else:
data[monkey["false"]]["items"].append(new)
monkey["items"].clear()
return math.prod(sorted(inspected)[-2:])
aoc_helper.lazy_test(day=11, year=2022, parse=parse_raw, solution=part_two)
aoc_helper.lazy_submit(day=11, year=2022, solution=part_one, data=data)
aoc_helper.lazy_submit(day=11, year=2022, solution=part_two, data=data)