From 8e84babc729e33460e9c88f92c51667bf8761fe3 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Tue, 14 Dec 2021 08:22:58 +0000 Subject: day 14 --- 14.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 14.py 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)) -- cgit v1.2.3-54-g00ecf