summaryrefslogtreecommitdiff
path: root/2024/22/python.py
diff options
context:
space:
mode:
authormhsn <mail@mhsn.net>2025-09-12 20:20:58 +0100
committermhsn <mail@mhsn.net>2025-09-12 20:36:09 +0100
commit6b733982f9f240c1c97f1fa705bfbe4cd93c640e (patch)
treedad623203c8bb40f372e0ea14479c2f564efda79 /2024/22/python.py
parent9299c4ef655b88eb8b571864c939c78b27f77723 (diff)
downloadaoc-6b733982f9f240c1c97f1fa705bfbe4cd93c640e.tar.gz
aoc-6b733982f9f240c1c97f1fa705bfbe4cd93c640e.zip
simplify python file structure
Diffstat (limited to '2024/22/python.py')
-rwxr-xr-x2024/22/python.py59
1 files changed, 59 insertions, 0 deletions
diff --git a/2024/22/python.py b/2024/22/python.py
new file mode 100755
index 0000000..98d8898
--- /dev/null
+++ b/2024/22/python.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+
+from collections import Counter, deque
+from fileinput import input
+from itertools import islice
+
+lines = [int(line.strip()) for line in input()]
+
+
+def secrets(secret):
+ x = secret
+ while True:
+ yield x
+ x ^= x << 6
+ x &= 0xFFFFFF
+ x ^= x >> 5
+ x &= 0xFFFFFF
+ x ^= x << 11
+ x &= 0xFFFFFF
+
+
+def prices(it):
+ for s in it:
+ yield s % 10
+
+
+def diff(it):
+ prev = next(it)
+ for curr in it:
+ yield curr, curr - prev
+ prev = curr
+
+
+def to_seqs(it, n=4):
+ head = map(lambda x: x[1], islice(it, n - 1))
+ q = deque(head, maxlen=n)
+ for price, diff in it:
+ q.append(diff)
+ yield price, tuple(q)
+
+
+def seq_sells(it):
+ sells = {}
+ for price, diff in it:
+ if diff in sells:
+ continue
+ sells[diff] = price
+ return sells
+
+
+best_seqs = Counter()
+for x in lines:
+ best_seqs += seq_sells(to_seqs(islice(diff(prices(secrets(x))), 2000)))
+
+silver = sum(next(islice(secrets(x), 2000, None)) for x in lines)
+gold = best_seqs.most_common(1)[0][1]
+
+print("silver:", silver)
+print("gold:", gold)