aboutsummaryrefslogtreecommitdiff
path: root/2022/11/solve.py
blob: eb2685ca6168e2fce5d1d62c1ea0f6ba807ae9bd (plain) (blame)
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
data = [
    [line.strip() for line in dat.split("\n")]
    for dat in open("input").read().split("\n\n")
    if dat != ""
]


def solve(part):
    monkeys = [
        {
            "items": [],
            "op": None,
            "divisibility": 1,
            "true": 0,
            "false": 0,
            "inspected": 0,
        }
        for i in range(len(data))
    ]

    # setup monkeys
    for i, block in enumerate(data):
        monkeys[i]["items"] = [
            int(item) for item in block[1].split(": ")[1].split(", ")
        ]
        monkeys[i]["op"] = block[2].split(": ")[1].replace("new = ", "")
        monkeys[i]["divisibility"] = int(block[3].split(" ")[-1])
        monkeys[i]["true"] = int(block[4].split(" ")[-1])
        monkeys[i]["false"] = int(block[5].split(" ")[-1])

    if part == 2:
        # evil muhahahaa
        common = eval(
            "*".join(str(monkey["divisibility"]) for monkey in monkeys)
        )

    for r in range(20 if part == 1 else 10000):
        current = 0
        while True:  # new round
            if current >= len(monkeys):
                break

            if len(monkeys[current]["items"]) == 0:
                current += 1
                continue

            monkeys[current]["inspected"] += 1
            old = monkeys[current]["items"].pop(0)
            lvl = eval(monkeys[current]["op"])
            lvl = int(lvl / 3) if part == 1 else lvl % common
            if lvl % monkeys[current]["divisibility"] == 0:
                monkeys[monkeys[current]["true"]]["items"].append(lvl)
            else:
                monkeys[monkeys[current]["false"]]["items"].append(lvl)

    bizz = sorted([monkey["inspected"] for monkey in monkeys])
    return bizz[-1] * bizz[-2]


print(f"Part 1: {solve(1)}")
print(f"Part 2: {solve(2)}")