-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday_11.py
68 lines (59 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
from dataclasses import dataclass
from functools import reduce
from typing import List
with open('inputs/day_11.txt', 'r') as f:
inputs = f.read()
@dataclass
class Monkey:
items: List[int]
operation: str
monkey_test: int
on_true_throw_to: int
on_false_throw_to: int
def eval(self):
return [eval(f'{item} {self.operation}') for item in self.items]
@staticmethod
def from_input(lines: str) -> 'Monkey':
rows = lines.split('\n')
for row in rows:
row = row.strip()
if row.startswith('Monkey'):
pass
if row.startswith('Starting items:'):
starting_items = row.replace(',', '').split(' ')[2:]
starting_items = [int(item) for item in starting_items]
if row.startswith('Operation:'):
operation = row.split('Operation: new = old ')[1].replace('* old', '** 2')
if row.startswith('Test: divisible by '):
test_divisible_by = int(row.split('Test: divisible by ')[1])
if row.startswith('If true: throw to monkey '):
on_true_throw_to = int(row.split('If true: throw to monkey ')[1])
if row.startswith('If false: throw to monkey '):
on_false_throw_to = int(row.split('If false: throw to monkey ')[1])
return Monkey(
items=starting_items,
operation=operation,
monkey_test=test_divisible_by,
on_true_throw_to=on_true_throw_to,
on_false_throw_to=on_false_throw_to
)
def solve():
monkeys = [Monkey.from_input(m) for m in inputs.split('\n\n')]
monkey_bznz = [0] * len(monkeys)
worry_treshhold = reduce(lambda x, y: x * y, [m.monkey_test for m in monkeys])
for _ in range(10000):
for i in range(len(monkeys)):
monkey = monkeys[i]
eval_items = monkey.eval()
eval_items = [item % worry_treshhold for item in eval_items]
# eval_items = [item//3 for item in eval_items]
monkey_bznz[i] += len(eval_items)
monkey.items = []
for item in eval_items:
if item % monkey.monkey_test == 0:
monkeys[monkey.on_true_throw_to].items.append(item)
else:
monkeys[monkey.on_false_throw_to].items.append(item)
monkey_bznz.sort()
print(monkey_bznz[-1] * monkey_bznz[-2])
#solve()