Motivation
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.
As I already tried some of the puzzles last year I wanted to see how far I could get this year.
Registration
To be able to unlock part 2 of every-day’s challenge by checking your answers for correctness you need to log in
https://adventofcode.com/2022/auth/login (I prefer github)
After login you can also compete with others via the leaderboard
Day 1 – Part 1
You can find the first exercise here https://adventofcode.com/2022/day/1
tl;dr; Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
calories = """1000
2000
3000
4000
5000
6000
7000
8000
9000
10000"""
In the sample data there are five groups each divided by two newlines.
So we can try to split the multi-line string into its parts and see if we get five groups:
def test_calc_split_calories():
list_cal = calories.split("\n\n")
assert len(list_cal) == 5
Yep, that works. Now we need to split every sub-string into sub-sub-strings.
For testing purposes we just split the first sub-string (index 0) and expect the sum to be 6000 (1000 + 2000 + 3000)
Because we are still dealing with strings we take a list comprehension to convert the list of sub-sub-strings into a list of integers.
def test_calc_individual_max_calories():
list_all_cal = calories.split("\n\n")
list_individual_cal = [int(x) for x in list_all_cal[0].split("\n")]
individual_cal = sum(list_individual_cal)
assert individual_cal == 6000
The next step is to iterate over all sub-strings and try to find out the maximum sum of individual calories.
def test_calc_overall_max_calories():
overall_max_cal = 0
overall_max_cal_index = 0
list_all_cal = calories.split("\n\n")
for i, list_cal in enumerate(list_all_cal):
list_individual_cal = [int(x) for x in list_cal.split("\n")]
sum_cal = sum(list_individual_cal)
if sum_cal > overall_max_cal:
overall_max_cal = sum_cal
overall_max_cal_index = i
assert overall_max_cal == 24000
assert overall_max_cal_index == 3
And now for the final part: We download the test data and save it to a text file called aoc_data_01.txt
Now we can read the text file and get the value to answer the question:
def test_calc_overall_max_calories_from_file():
with open("aoc_data_01.txt", "r") as f:
data = f.read()
overall_max_cal = 0
overall_max_cal_index = 0
list_all_cal = data.split("\n\n")
for i, list_cal in enumerate(list_all_cal):
list_individual_cal = [int(x) for x in list_cal.split("\n")]
sum_cal = sum(list_individual_cal)
if sum_cal > overall_max_cal:
overall_max_cal = sum_cal
overall_max_cal_index = i
assert overall_max_cal == 67027
assert overall_max_cal_index == 12
Advent of Code 2022 Day 1 Part 2