Advent of Code 2024 — Day 1: Historian Hysteria
Advent of Code 2024 is here, so let's get into day 1.
Part 1
The Chief Historian went missing, and the Elves' notes are a mess: two lists of location IDs that should match but don't.
Out of the story, the goal is simple. Sort both lists, pair the numbers up in order (smallest with smallest, and so on), then add up how far apart each pair is.
The example input:
3 4
4 3
2 5
1 3
3 9
3 3
Sorted, the left list is 1 2 3 3 3 4 and the right one is 3 3 3 4 5 9. Now the distances:
1 and 3 => 2
2 and 3 => 1
3 and 3 => 0
3 and 4 => 1
3 and 5 => 2
4 and 9 => 5
2 + 1 + 0 + 1 + 2 + 5 = 11, and that's the answer for the example.
Let's code it. I read the file line by line and split each line into its two numbers. Then I sort each side on its own, zip them back together, and sum the differences.
def solve_part_1():
pairs = []
with open("input.txt", "r") as f:
lines = f.read().strip().split("\n")
for l in lines:
pairs.append(list(map(int, l.split(" "))))
pairs.sort()
l = [p[0] for p in pairs]
r = [p[1] for p in pairs]
l.sort()
r.sort()
spairs = list(zip(l, r))
sol = 0
for p in spairs:
sol += abs(p[0] - p[1])
return solPart 2
Turns out a lot of IDs show up in both lists, so maybe they aren't that different after all.
This time we need a similarity score: take each number in the left list, multiply it by how many times it appears in the right list, and sum everything.
With the same example:
3 appears 3 times => 9
4 appears 1 time => 4
2 appears 0 times => 0
1 appears 0 times => 0
3 appears 3 times => 9
3 appears 3 times => 9
9 + 4 + 0 + 0 + 9 + 9 = 31. The three 3s on the left each count, that's where most of the score comes from.
No sorting needed here, just a count for every number on the left.
def solve_part_2():
pairs = []
with open("input.txt", "r") as f:
lines = f.read().strip().split("\n")
for l in lines:
pairs.append(list(map(int, l.split(" "))))
l = [p[0] for p in pairs]
r = [p[1] for p in pairs]
sol = 0
for v in l:
sol += v * r.count(v)
return solAnd that's day 1 done.