Jesper Dramsch , , read in 3 minutes

In this little series, I want to write about the thought processes I have behind solving the puzzles presented in Advent of Code.

During the Advent of Code small coding puzzles are presented with varying levels of difficulty. They're always Christmas-themed text puzzles where you help elves out of some mess to save the holidays. The puzzles are deliberately ambiguous to not bias puzzlers into a certain solution, they always have an example input in the text to explain some details and an input file for each day that comes in the form of a text file you can download. The solution is a simple number or a string you enter, which is checked by the website automatically. After you finish part 1, part 2 unlocks, which is a variation on part 2. This can be a little twist on part 1 or a large twist that changes the problem formulation into a problem that would take brute force solutions to compute longer than the heat death of the universe would take.

Find my solutions here: github.com/JesperDramsch/advent-of-code

Let's start with day 1, which is usually nice and easy. These descriptions won't be a perfect narrative, but rather how I think about these problems and where I see different solutions. I apologise for the possibility of rambling!

The example input

When you hear expert solvers, they will usually look at the example input first. I don't always do this, but here it was very obvious that those numbers would be grouped in some way:

1000
2000
3000

4000

5000
6000

7000
8000
9000

10000

We already know that we can split each group by \n\n, but in my case I split all inputs by \n by default in my utility data loader anyways.

The Implementation

Instead of splitting in two newlines, I decided to use a simple loop through the list of snacks, that would append the finalised sum to a list on an empty line.

for line in data:
    if line == "":
        elves.append(calories)
        calories = 0
    else:
        calories += int(line)

That causes another problem, that your last sum is missed, so I decided to append an extra empty line to the data.

Alternatively, there would've been a nice way extracting the numbers with regex, for example that doesn't need a full Python loop.

Part 2

The part 2 was fairly straightforward, since I already had a list of sums of calories.

So instead of max() I could simply change to a sum():

if part == 1:
    return max(day.data)
if part == 2:
    return sum(sorted(day.data, reverse=True)[:3])

Error log

I decided to write an error log for my 2022 Advent of Code, but I only remembered on day 3.