forked from JEPooley/2021-AdventOfCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart-1.py
45 lines (30 loc) · 1.03 KB
/
part-1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Day 14 : Extended Polymerization
## Part 1
import re
from collections import Counter
def argstring(string, substring):
return [m.start() + 1 for m in re.finditer(f"(?={substring})", string)]
def insert_elements(insertion_map, string):
insertions = {}
for key, value in insertion_map.items():
idxs = argstring(string, key)
insertions.update({idx: value for idx in idxs})
for idx in sorted(insertions, reverse=True):
value = insertions[idx]
string = string[:idx] + value + string[idx:]
return string
# load rules
text = open("rules.txt").read().split("\n\n")
seed = text[0]
rules = [rule.split(" -> ") for rule in text[1].split("\n")]
# create insertion map
insertion_map = {key: value for key, value in rules}
# insert elements
steps = 10
for i in range(steps):
seed = insert_elements(insertion_map, seed)
# find most and least common
counter = Counter(seed)
most_common = counter.most_common()[0]
least_common = counter.most_common()[-1]
print(most_common[1] - least_common[1])