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 2022/25

+47
+47
2022/day25.py
··· 1 + import fileinput 2 + 3 + SNAFU_DIGITS = { 4 + '2': 2, 5 + '1': 1, 6 + '0': 0, 7 + '-': -1, 8 + '=': -2, 9 + } 10 + REVERSE_DIGITS = {v: k for k, v in SNAFU_DIGITS.items()} 11 + 12 + 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] 21 + 22 + 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 28 + 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))