My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add 2021/14

+47
+47
2021/day14.py
··· 1 + import fileinput 2 + from collections import Counter, defaultdict, deque, namedtuple # NOQA 3 + 4 + # Read problem input. 5 + data = ''.join([line for line in fileinput.input()]) 6 + groups = [g.split('\n') for g in data.split('\n\n')] 7 + 8 + 9 + POLYMER = groups[0][0] 10 + MAPPING = {} 11 + 12 + for line in groups[1]: 13 + a, b = line.split(' -> ') 14 + MAPPING[a] = b 15 + 16 + 17 + # COUNTS maps bigrams to their counts in the underlying polymer. 18 + COUNTS = Counter() 19 + 20 + 21 + for i in range(len(POLYMER)-1): 22 + COUNTS[POLYMER[i:i+2]] += 1 23 + 24 + 25 + for iteration in range(1, 40 + 1): 26 + new_counts = Counter() 27 + 28 + for bigram, num in COUNTS.items(): 29 + insertion = MAPPING[bigram] 30 + 31 + new_counts[bigram[0] + insertion] += num 32 + new_counts[insertion + bigram[1]] += num 33 + 34 + COUNTS = new_counts 35 + 36 + if iteration in (10, 40): 37 + # Compute counts of individual letters from bigram counts. 38 + letter_counts = Counter() 39 + 40 + for bigram, num in COUNTS.items(): 41 + letter_counts[bigram[0]] += num 42 + letter_counts[bigram[1]] += num 43 + 44 + frequencies = zip(*letter_counts.most_common())[1] 45 + most = (frequencies[0] + 1) // 2 46 + least = (frequencies[-1] + 1) // 2 47 + print "Part 1:" if iteration == 10 else "Part 2:", most - least