diff options
-rw-r--r-- | 14.py | 32 |
1 files changed, 32 insertions, 0 deletions
@@ -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)) |