summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTomasz Kramkowski <tk@the-tk.com>2021-12-14 08:22:58 +0000
committerTomasz Kramkowski <tk@the-tk.com>2021-12-14 08:22:58 +0000
commit8e84babc729e33460e9c88f92c51667bf8761fe3 (patch)
tree7abfdacc9e14998f543e6375b7c9c29ed8d61648
parent51da7613eb93ffd3851970d2f51530732bc47c53 (diff)
downloadaoc2021-8e84babc729e33460e9c88f92c51667bf8761fe3.tar.gz
aoc2021-8e84babc729e33460e9c88f92c51667bf8761fe3.tar.xz
aoc2021-8e84babc729e33460e9c88f92c51667bf8761fe3.zip
day 14
-rw-r--r--14.py32
1 files changed, 32 insertions, 0 deletions
diff --git a/14.py b/14.py
new file mode 100644
index 0000000..e2a8e05
--- /dev/null
+++ b/14.py
@@ -0,0 +1,32 @@
+from collections import Counter
+from itertools import pairwise
+from utils import open_day
+
+PairCounts = Counter[tuple[str, str]]
+
+with open_day(14) as f:
+ chunks = f.read().rstrip().split('\n\n')
+ template = chunks[0]
+ rules = { (p[0][0], p[0][1]): p[1] for p in (l.split(' -> ') for l in chunks[1].split('\n')) }
+
+def step(pairs: PairCounts, rules: list[str, str]) -> PairCounts:
+ newcount: PairCounts = Counter()
+ for pair, count in pairs.items():
+ insert = rules[pair]
+ newcount[(pair[0], insert)] += count
+ newcount[(insert, pair[1])] += count
+ return newcount
+
+def solution(pairs: PairCounts, template: str) -> int:
+ c = Counter()
+ for pair, count in pairs.items():
+ c[pair[0]] += count
+ c[template[-1]] += 1
+ common = c.most_common()
+ return common[0][1] - common[-1][1]
+
+pairs = Counter(pairwise(template))
+for _ in range(10): pairs = step(pairs, rules)
+print(solution(pairs, template))
+for _ in range(30): pairs = step(pairs, rules)
+print(solution(pairs, template))