48 lines
1.6 KiB
Python
48 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(pairs: Dict[str, int], charcount: Dict[str, int], inserts: Dict[str, str], count: 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
|
|
|
|
|
|
class Day(AOCDay):
|
|
test_solutions_p1 = [1588, 3230]
|
|
test_solutions_p2 = [2188189693529, 3542388214529]
|
|
|
|
def part1(self) -> Any:
|
|
pairs, charcount, inserts = getInitialDicts(self.getInput())
|
|
insert(pairs, charcount, inserts, 10)
|
|
return max(charcount.values()) - min(charcount.values())
|
|
|
|
def part2(self) -> Any:
|
|
pairs, charcount, inserts = getInitialDicts(self.getInput())
|
|
insert(pairs, charcount, inserts, 40)
|
|
return max(charcount.values()) - min(charcount.values())
|