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.

Update 2022/25

+17 -32
+17 -32
2022/day25.py
··· 1 1 import fileinput 2 + from collections import Counter 3 + from itertools import zip_longest 2 4 3 5 SNAFU_DIGITS = { 4 6 '2': 2, ··· 10 12 REVERSE_DIGITS = {v: k for k, v in SNAFU_DIGITS.items()} 11 13 12 14 13 - def decimal_to_base(n, b): 14 - if n == 0: 15 - return [0] 16 - digits = [] 17 - while n: 18 - digits.append(int(n % b)) 19 - n //= b 20 - return digits[::-1] 15 + # Read problem input and solve problem. 16 + nums = [line.strip() for line in fileinput.input()] 17 + remainder = Counter() 18 + part_1 = '' 21 19 20 + for i, place in enumerate(zip_longest(*(reversed(n) for n in nums), fillvalue='0')): 21 + count = sum(SNAFU_DIGITS[c] for c in place) + remainder[i] 22 + while not -2 <= count <= 2: 23 + if count < 0: 24 + remainder[i+1] -= 1 25 + count += 5 26 + else: 27 + remainder[i+1] += 1 28 + count -= 5 22 29 23 - def snafu_to_decimal(s): 24 - n = 0 25 - for i, c in enumerate(reversed(s)): 26 - n += SNAFU_DIGITS[c] * (5 ** i) 27 - return n 30 + part_1 = REVERSE_DIGITS[count] + part_1 28 31 29 - 30 - def decimal_to_snafu(n): 31 - quinary_digits = decimal_to_base(n, 5) 32 - snafu_digits = [] 33 - 34 - # Iterate in reverse order through the base-5 digits; if a number larger 35 - # than 2 is found, add 1 to the next "place" and take the remainder. 36 - for i, n in enumerate(reversed(quinary_digits)): 37 - if n >= 3: 38 - quinary_digits[-(i+2)] += 1 39 - n -= 5 40 - snafu_digits = [REVERSE_DIGITS[n]] + snafu_digits 41 - 42 - return ''.join(snafu_digits) 43 - 44 - 45 - # Read problem input and solve problem. 46 - total = sum(snafu_to_decimal(line.strip()) for line in fileinput.input()) 47 - print("Part 1:", decimal_to_snafu(total)) 32 + print("Part 1:", part_1)