Published on

Advent of Code 2022: Day 1 Solution

  • avatar
    Tinker Assist


As I gear up for Advent of Code 2023, I thought I would post some of my solutions from Advent of Code 2022! Admittedly, I have only completed 10 of the 2022 puzzles as I didn't learn about it until the end of December. However, I plan to stay deligent and set aside plenty of time to complete each day's puzzle this year.


Read the Puzzle Input File

We will save our puzzle input in "day1_input.txt" and then read from that file.

file = open("day1_p1_input.txt", "r")
input =

We will then break up the input by line:

input_list = input.split('\n')

Part 1 Solution

Now, in solving the problem, the first thing we should do is create a list of each elf's calorie sum. We can use each null input line as the delimeter between one elf and the next. My implementation looks as follows

elf_calories = [] # list of each elf's calorie sum
calorie_counter = 0 # calorie counter for current elf

# loop through each line in our input file
for line in input_list:
    # elf delimeter
    if line == '':
        elf_calories.append(calorie_counter) # add the current sum to our list 
        calorie_counter = 0 # reset our calorie counter for next elf
        calorie_counter += int(line) # add input to our calorie counter

Now that we have a list of each elf's calorie sum, we need to find the one with the largest sum. We can do this by sorting our list from largest to smallest and then printing the value in the first index.

# sort the list from largest to smallest
elf_calories = sorted(elf_calories, reverse=True)

# print the # of calories the elf with the most has

Part 2 Solution

For part 2, we must adapt our code to consider three elves with the largest calorie sum. If we are feeling lazy, we could simply add the first through third indexes as follows

print(elf_calories[0] + elf_calories[1] + elf_calories[2])

But, let's instead adapt our code in a way that can be easily used for any number of elves we would want to consider in our sum. To do this, we will create a new variable num_carriers to represent the # of top calorie-carrying elves we need to sum. Then, we will loop through the top calorie-carriers and print the sum

num_carriers = 3 # number of elves contributing to the calorie sum. (part 1 - 1; part 2 - 3)
total = 0
for i in range(0, num_carriers):
    total += elf_calories[i]


Full code

Get the full, cleaned-up code here.