~noelle/aoc-2021

e6f3ddf42234f1445cc49b1aa9782defe59ce156 — Noelle Leigh 2 years ago b88fb16
14_2
2 files changed, 34 insertions(+), 1 deletions(-)

M 14/example.txt
A 14/puzzle_2.py
M 14/example.txt => 14/example.txt +1 -1
@@ 15,4 15,4 @@ BN -> B
BB -> N
BC -> B
CC -> N
CN -> C
CN -> C
\ No newline at end of file

A 14/puzzle_2.py => 14/puzzle_2.py +33 -0
@@ 0,0 1,33 @@
"""
Solution for AoC 2021 14 Puzzle 2

cat input.txt | python puzzle_2.py

We don't actually need to construct a giant string, we just care about character counts.

Ref: https://markestedt.hashnode.dev/advent-of-code-2021-day-14
"""
import sys
from itertools import pairwise
from typing import Counter

if __name__ == "__main__":
    template = next(sys.stdin).strip()
    next(sys.stdin)
    rules = dict(map(lambda line: line.strip().split(" -> ", maxsplit=1), sys.stdin))

    pair_counter = Counter(map(lambda pair: "".join(pair), pairwise(template)))
    char_counter = Counter(template)
    for step in range(1, 40 + 1):
        pair_counter_changes = Counter()
        for pair, pair_count in pair_counter.items():
            insertion = rules[pair]
            pair_counter_changes[pair[0] + insertion] += pair_count
            pair_counter_changes[insertion + pair[1]] += pair_count
            pair_counter_changes[pair] -= pair_count
            char_counter[insertion] += pair_count
        pair_counter += pair_counter_changes

    element_counts = char_counter.most_common()
    value = element_counts[0][1] - element_counts[-1][1]
    sys.stdout.write(str(value))