|
| 1 | +from functools import partial |
| 2 | +from math import prod |
| 3 | +from operator import add, mul |
| 4 | + |
| 5 | +from more_itertools import chunked |
| 6 | + |
| 7 | +stub = lambda a, b, op: {"+": add, "*": mul}[op](a, b) |
| 8 | + |
| 9 | +with open("input.txt") as f: |
| 10 | + descs = list(chunked([x.strip() for x in f], 7)) |
| 11 | + |
| 12 | +monkeys = [] |
| 13 | +for desc in descs: |
| 14 | + m = {"items": [int(i) for i in desc[1].split(":")[1].split(",")], |
| 15 | + "test": int(desc[3].split()[-1]), |
| 16 | + True: int(desc[4].split()[-1]), |
| 17 | + False: int(desc[5].split()[-1]), |
| 18 | + "count": 0} |
| 19 | + chunks = desc[2].split("=")[1].strip() |
| 20 | + if chunks == "old * old": |
| 21 | + m["func"] = lambda x: x*x |
| 22 | + else: |
| 23 | + _, op, var2 = chunks.split() |
| 24 | + m["func"] = partial(stub, b=int(var2), op=op) |
| 25 | + monkeys.append(m) |
| 26 | + |
| 27 | +z = prod(m["test"] for m in monkeys) |
| 28 | + |
| 29 | +for k in range(10_000): # replace with 20 for Part 1 |
| 30 | + for m in monkeys: |
| 31 | + while len(m["items"]) > 0: |
| 32 | + m["count"] += 1 |
| 33 | + i = m["func"](m["items"].pop(0)) |
| 34 | + # i //= 3 # Part 1 |
| 35 | + i %= z # Part 2 |
| 36 | + monkeys[m[i % m["test"] == 0]]["items"].append(i) |
| 37 | + |
| 38 | +print(prod(sorted([m["count"] for m in monkeys])[-2:])) |
0 commit comments