Advent of Code 2022 day 25
A nice and easy end to the puzzles. I look forward to next year!
from math import ceil
with open("25.txt") as f:
lines = f.read().splitlines()
snafu_to_dec_char = {
"2": 2,
"1": 1,
"0": 0,
"-": -1,
"=": -2,
}
dec_to_snafu_char = {
2: "2",
1: "1",
0: "0",
-1: "-",
-2: "=",
}
def snafu_to_dec(line):
dec = 0
power = 0
for coeff in reversed(line):
dec += snafu_to_dec_char[coeff]*(5**power)
power += 1
return dec
def dec_to_snafu(x):
def get_coeffs(x):
coeffs = []
max_power = ceil(x**(1/5))
for power in reversed(range(max_power)):
coeff = x // 5**power
coeffs.append(coeff)
x -= (coeff*(5**power))
return coeffs
def carry_overs(coeffs):
new_coeffs = [0] + coeffs
for i in range(len(new_coeffs)):
while new_coeffs[-i] > 2:
new_coeffs[-i-1] += 1
new_coeffs[-i] -= 5
return new_coeffs
coeffs = get_coeffs(x)
latest_coeffs = carry_overs(coeffs)
return "".join(dec_to_snafu_char[x] for x in latest_coeffs).lstrip("0")
print(dec_to_snafu(sum(snafu_to_dec(line) for line in lines)))