AOC 2024 Day One: Historian Hysteria
Advent of Code is truly the most wonderful time of the year. In 2024, I’m going to be solving the puzzles using Python, as I always often do.
Let’s get started.
Problem | Solution |
Part One
Basically we have a two lists of numbers that look like:
3 4
4 3
2 5
1 3
3 9
3 3
We’re being asked to calculate the difference between the two lists, but with a twist: the numbers are unsorted, and we need to compare the smallest in each list together, then the second-smallest, etc., and the sum of the absolute difference between the two lists, compared pairwise like that, is the solution to the problem.
This is pretty easy. It’s day one, after all.
Let’s parse the input.
import sys
list_a = []
list_b = []
input = sys.stdin.read()
for line in input.splitlines():
[a, b] = list(map(int, line.strip().split()))
list_a.append(a)
list_b.append(b)
Now that that’s out of the way, let’s just sort the lists and compare them pairwise.
list_a.sort()
list_b.sort()
part_one = sum(abs(a-b) for (a, b) in zip(list_a, list_b))
print(part_one)
Using zip
to combine two lists and then destructuring the resulting tuples inside a comprehension feels like the most Python-y thing a person can do.
And there we have it.
Part Two
Same input, but now it’s saying that the answer is the sum of the first list of numbers multiplied by how many times the digit appears in the second list. We can use the Counter
class from collections
to make this a two line answer.
from collections import Counter
c = Counter(list_b)
part_two = sum(a * c.get(a, 0) for a in list_a)
print(part_two)
And we’re done.
The early puzzles tend to be pretty easy, and this was no exception. But don’t let the easy days lull you into a false sense of security… 😅