day 11 python tweaks

main
magical 2022-12-10 23:38:51 -08:00
parent 4fc545ac39
commit 648ce83517
1 changed files with 9 additions and 10 deletions

View File

@ -1,4 +1,5 @@
from collections import Counter, namedtuple from collections import Counter, namedtuple
from copy import deepcopy
import math import math
Monkey = namedtuple('Monkey', 'index, op, divisor, target') Monkey = namedtuple('Monkey', 'index, op, divisor, target')
@ -20,14 +21,14 @@ def parse(input):
int(lines[5].split()[-1]), int(lines[5].split()[-1]),
int(lines[4].split()[-1]), int(lines[4].split()[-1]),
] ]
monkeys.append(Monkey(items, op, divisor, target)) monkeys.append(Monkey(i, op, divisor, target))
return monkeys, items return monkeys, items
def play(monkeys, items, rounds=1, N=None): def play(monkeys, items, rounds=1, N=None):
throws = Counter() throws = Counter()
for _ in range(rounds): for _ in range(rounds):
for i, m in enumerate(monkeys): for m in monkeys:
for j, x in enumerate(items[i]): for x in items[m.index]:
if N: if N:
nx = m.op(x) % N nx = m.op(x) % N
else: else:
@ -35,8 +36,9 @@ def play(monkeys, items, rounds=1, N=None):
trg = m.target[nx % m.divisor == 0] trg = m.target[nx % m.divisor == 0]
#print(f'{i}: {x} -> {nx}. throwing to {trg}') #print(f'{i}: {x} -> {nx}. throwing to {trg}')
items[trg].append(nx) items[trg].append(nx)
throws[i] += len(items[i]) throws[m.index] += len(items[m.index])
items[i] = [] items[m.index] = []
show(items)
return throws return throws
def show(items): def show(items):
@ -58,14 +60,11 @@ def main():
#print(monkeys) #print(monkeys)
show(items) show(items)
tmp = {i: list(xs) for i, xs in items.items()} throws = play(monkeys, deepcopy(items), rounds=20)
throws = play(monkeys, tmp, rounds=20)
show(tmp)
print(monkeybusiness(throws)) print(monkeybusiness(throws))
N = lcm(m.divisor for m in monkeys) N = lcm(m.divisor for m in monkeys)
throws = play(monkeys, items, rounds=10000, N=N) throws = play(monkeys, deepcopy(items), rounds=10000, N=N)
show(items)
print(monkeybusiness(throws)) print(monkeybusiness(throws))
main() main()