59 lines
1.6 KiB
Python
59 lines
1.6 KiB
Python
from tools.aoc import AOCDay
|
|
from typing import Any, Dict, List
|
|
|
|
|
|
def getInitialDicts(puzzle: List[str]) -> (Dict[str, int], Dict[str, int], Dict[str, str]):
|
|
polymer = puzzle[0]
|
|
inserts = {}
|
|
for p1 in puzzle[2:]:
|
|
pair, insert_char = p1.split(" -> ")
|
|
inserts[pair] = insert_char
|
|
|
|
pairs = {}
|
|
charcount = {}
|
|
for x in range(len(polymer) - 1):
|
|
pairs[polymer[x:x + 2]] = pairs.get(polymer[x:x + 2], 0) + 1
|
|
charcount[polymer[x]] = charcount.get(polymer[x], 0) + 1
|
|
|
|
charcount[polymer[-1]] = charcount.get(polymer[-1], 0) + 1
|
|
|
|
return pairs, charcount, inserts
|
|
|
|
|
|
def insert(count: int, pairs: Dict[str, int], charcount: Dict[str, int], inserts: Dict[str, str]) -> int:
|
|
for _ in range(count):
|
|
new_pairs = {}
|
|
for p in pairs:
|
|
p1 = p[0] + inserts[p]
|
|
p2 = inserts[p] + p[1]
|
|
charcount[inserts[p]] = charcount.get(inserts[p], 0) + pairs[p]
|
|
new_pairs[p1] = new_pairs.get(p1, 0) + pairs[p]
|
|
new_pairs[p2] = new_pairs.get(p2, 0) + pairs[p]
|
|
pairs = new_pairs
|
|
|
|
return max(charcount.values()) - min(charcount.values())
|
|
|
|
|
|
class Day(AOCDay):
|
|
inputs = [
|
|
[
|
|
(1588, "test_input14"),
|
|
(3230, "input14")
|
|
],
|
|
[
|
|
(2188189693529, "test_input14"),
|
|
(3542388214529, "input14")
|
|
]
|
|
]
|
|
|
|
def part1(self) -> Any:
|
|
return insert(10, *getInitialDicts(self.getInput()))
|
|
|
|
def part2(self) -> Any:
|
|
return insert(40, *getInitialDicts(self.getInput()))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
day = Day(14)
|
|
day.run(verbose=True)
|