summaryrefslogtreecommitdiffstats
path: root/14.py
blob: e2a8e059dd18a822c1fee3158ed0b73ddf24b49a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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))