-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday14.py
59 lines (47 loc) · 1.57 KB
/
day14.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from util import Day
from aocd import submit
from collections import Counter
def parse_input(data):
template = data[0]
instructions = dict(line.split(" -> ") for line in data[2:])
return template, instructions
def process_instructions(steps, template, instructions):
# Create Counters for pairs and letters
pairs = Counter([a + b for (a, b) in zip(template, template[1:])])
letters = Counter(template)
# Iterate through steps
for _ in range(steps):
# Iterate through pair counts (copy to modify pair in loop)
for pair, count in pairs.copy().items():
# Check if pair is in instruction
c = instructions.get(pair)
if c is not None:
# Split pair into two letters
a, b = pair
# Remove pair from pairs
pairs[pair] -= count
# Add the two new pair to pairs
pairs[a + c] += count
pairs[c + b] += count
# Add new letter
letters[c] += count
return letters
def main(day, part=1):
day.data = parse_input(data=day.data)
if part == 1:
steps = 10
if part == 2:
steps = 40
count = process_instructions(steps, *day.data).most_common()
return count[0][1] - count[-1][1]
if __name__ == "__main__":
day = Day(14)
day.download()
day.load(typing=str)
p1 = main(day)
print(p1)
submit(p1, part="a", day=14, year=2021)
day.load(typing=str)
p2 = main(day, part=2)
print(p2)
submit(p2, part="b", day=14, year=2021)