Learning Python with Advent of Code Walkthroughs

Dazbo's Advent of Code solutions, written in Python


Advent of Code 2022 - Day 25

Day 25: Full of Hot Air

Useful Links

Concepts and Packages Demonstrated


Problem Intro

We have a bunch of hot air balloons, and we’re told we need to pre-heat their fuel using our fuel heating machine. It needs to be calibrated in advance. To do this, we need to tell the machine how much fuel we need to heat. To determine the total amount of fuel to heat, we just need to add up the fuel quantities from each hot air balloon.

Unfortunately, all fuel quantities are expressed in SNAFU format. This is our input data. E.g.


SNAFU is a variant of base-5. But instead of using digit values 0 through 4, it instead uses these digits:

Digit Decimal equivalent
= -2
- -1
0 0
1 1
2 2

Part 1

What SNAFU number do you supply to Bob’s console?

We need to determine the sum of all the SNAFU numbers in our input. But this sum must be expressed in SNAFU!

Here’s my strategy:

Here is the code:

from pathlib import Path
import time

SCRIPT_DIR = Path(__file__).parent
# INPUT_FILE = Path(SCRIPT_DIR, "input/sample_input.txt")
INPUT_FILE = Path(SCRIPT_DIR, "input/input.txt")

snafu_to_dec = {
    '2': 2,
    '1': 1,
    '0': 0,
    '-': -1,
    '=': -2

int_to_snafu = {v:k for k,v in snafu_to_dec.items()}

def main():
    with open(INPUT_FILE, mode="rt") as f:
        data = f.read().splitlines()
def add_snafu(nums: list[str]) -> str:
    """ Add up snafu digits with column carry, just like any other base system.
    All the input digits are in snafu format, so are passed as str.
    Add up decimal values, calculate the carries, and convert the current column to snafu. """
    max_cols = max(len(num) for num in nums) # the longest digit in our input
    snafu_total_digits = []
    carry = 0
    for col in range(max_cols): # add up ALL numbers from right to left
        sum_col = carry # carry this number from previous column
        for num in nums:
            if col < len(num): # We need to include this number in the column addition
                # get the appropriate snafu digit from this number, convert to dec for addition
                sum_col += snafu_to_dec[num[len(num)-1-col]]
        carry = 0 # reset carry
        while sum_col > 2:
            # every unit carried is worth 5 from the column before
            carry += 1
            sum_col -= 5
        while sum_col < -2: # since snafu digits can be negative, we need to handle this
            carry -= 1
            sum_col += 5


    return (''.join(snafu_total_digits[::-1]))  

if __name__ == "__main__":
    t1 = time.perf_counter()
    t2 = time.perf_counter()
    print(f"Execution time: {t2 - t1:0.4f} seconds")

Part 2

There is no Part 2. Hurrah!!


Here’s the output:

Execution time: 0.0051 seconds

That’s it! 2022 AoC is done!

I hope you’ve found these walkthroughs useful!