Taddeus Kroes 3 lat temu
rodzic
commit
d036b8030b
2 zmienionych plików z 86 dodań i 0 usunięć
  1. 31 0
      2022/11_monkeys.py
  2. 55 0
      2022/input/11

+ 31 - 0
2022/11_monkeys.py

@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+import sys
+from operator import add, mul, pow
+from functools import reduce
+
+def parse(f):
+    for line in f:
+        if line.startswith('  Starting items:'):
+            items = tuple(map(int, line.split(':')[1].split(', ')))
+            opstr, amount = next(f).replace('* old', '** 2').split()[-2:]
+            op = {'+': add, '*': mul, '**': pow}[opstr], int(amount)
+            throws = tuple(int(next(f).rsplit(' ', 1)[1]) for _ in range(3))
+            yield items, op, throws
+
+def business(monkeys, rounds, divisor):
+    queues = [list(items) for items, _, _ in monkeys]
+    inspects = [0] * len(monkeys)
+    modulus = reduce(mul, (div for _, _, (div, _, _) in monkeys))
+    for _ in range(rounds):
+        for i, (_, (op, amount), (div, true, false)) in enumerate(monkeys):
+            items = queues[i]
+            for item in items:
+                worry = op(item, amount) // divisor % modulus
+                queues[false if worry % div else true].append(worry)
+            inspects[i] += len(items)
+            items.clear()
+    return mul(*sorted(inspects)[-2:])
+
+monkeys = list(parse(sys.stdin))
+print(business(monkeys, 20, 3))
+print(business(monkeys, 10000, 1))

+ 55 - 0
2022/input/11

@@ -0,0 +1,55 @@
+Monkey 0:
+  Starting items: 59, 65, 86, 56, 74, 57, 56
+  Operation: new = old * 17
+  Test: divisible by 3
+    If true: throw to monkey 3
+    If false: throw to monkey 6
+
+Monkey 1:
+  Starting items: 63, 83, 50, 63, 56
+  Operation: new = old + 2
+  Test: divisible by 13
+    If true: throw to monkey 3
+    If false: throw to monkey 0
+
+Monkey 2:
+  Starting items: 93, 79, 74, 55
+  Operation: new = old + 1
+  Test: divisible by 2
+    If true: throw to monkey 0
+    If false: throw to monkey 1
+
+Monkey 3:
+  Starting items: 86, 61, 67, 88, 94, 69, 56, 91
+  Operation: new = old + 7
+  Test: divisible by 11
+    If true: throw to monkey 6
+    If false: throw to monkey 7
+
+Monkey 4:
+  Starting items: 76, 50, 51
+  Operation: new = old * old
+  Test: divisible by 19
+    If true: throw to monkey 2
+    If false: throw to monkey 5
+
+Monkey 5:
+  Starting items: 77, 76
+  Operation: new = old + 8
+  Test: divisible by 17
+    If true: throw to monkey 2
+    If false: throw to monkey 1
+
+Monkey 6:
+  Starting items: 74
+  Operation: new = old * 2
+  Test: divisible by 5
+    If true: throw to monkey 4
+    If false: throw to monkey 7
+
+Monkey 7:
+  Starting items: 86, 85, 52, 86, 91, 95
+  Operation: new = old + 6
+  Test: divisible by 7
+    If true: throw to monkey 4
+    If false: throw to monkey 5