Last active
May 9, 2022 06:21
-
-
Save Mu-adventofcode/238ae4e3b8f24650fae7e2338e189e18 to your computer and use it in GitHub Desktop.
Advent of Code 2021 day 14 part 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from collections import Counter, defaultdict | |
with open("input_14.txt") as f: | |
template = f.readline().strip() | |
rules = { | |
tuple(pair): insert | |
for pair, insert in re.findall(r"(..) -> (.)", f.read()) | |
} | |
elem_frst = template[0] | |
elem_last = template[-1] | |
pair_cnt = Counter(zip(template, template[1:])) | |
for _ in range(40): | |
tmp = defaultdict(int) | |
for (ch0, ch1), ins in rules.items(): | |
tmp[ch0, ins] += pair_cnt[ch0, ch1] | |
tmp[ins, ch1] += pair_cnt[ch0, ch1] | |
pair_cnt = tmp | |
elem_cnt = defaultdict(float) | |
for (ch0, ch1), cnt in pair_cnt.items(): | |
elem_cnt[ch0] += cnt / 2 | |
elem_cnt[ch1] += cnt / 2 | |
elem_cnt[elem_frst] += 0.5 | |
elem_cnt[elem_last] += 0.5 | |
print(int(max(elem_cnt.values()) - min(elem_cnt.values()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment