diff options
author | Tomasz Kramkowski <tk@the-tk.com> | 2021-12-14 08:22:58 +0000 |
---|---|---|
committer | Tomasz Kramkowski <tk@the-tk.com> | 2021-12-14 08:22:58 +0000 |
commit | 8e84babc729e33460e9c88f92c51667bf8761fe3 (patch) | |
tree | 7abfdacc9e14998f543e6375b7c9c29ed8d61648 | |
parent | 51da7613eb93ffd3851970d2f51530732bc47c53 (diff) | |
download | aoc2021-8e84babc729e33460e9c88f92c51667bf8761fe3.tar.gz aoc2021-8e84babc729e33460e9c88f92c51667bf8761fe3.tar.xz aoc2021-8e84babc729e33460e9c88f92c51667bf8761fe3.zip |
day 14
-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)) |