Advent of Code 2024, Day 1
Part One
You are given a file with two columns of integers. They first ask you to pair up the ranked column numbers, i.e.:
Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on.
Then, you are required to compute the total difference defined as the sum of the absolute differences between the pairs. This is the answer to the puzzle.
My puzzle input has 1000 pairs. The first ten lines are:
88159 51481
66127 31794
71500 84893
59372 58807
97356 27409
31813 76811
58538 17103
91555 61602
64368 29057
93218 29845
Reading the input file was very easy. The Import
function is very flexible.
Indexing seems very expressive. The keyword for all the rows is All
instead of a colon (:
) like in other languages (e.g., Python).
The computation of the total distance is a one-liner, and I liked that they are all built-in functions (no library import, e.g., numpy
in Python).
lists = Import["input.txt", "Table"]
leftList = lists[[All, 1]]
rightList = lists[[All, 2]]
totalDistance = Total[Abs[Sort[leftList] - Sort[rightList]]]
The total distance was 1,579,939.
Part Two
The second part was about computing a similarity score defined as the sum of the products of each number in the left column times the number of times that number appears in the right column.
Function Count[list, pattern]
finds the number of times pattern
occurs in list
. I fixed list
to be the right column and made pattern
to be each value in the left column. This is done by mapping an anonymous function with variable pattern
to each element of the left column.
Anonymous functions can be written as expressions in terms of an argument placeholder (#
) and are denoted by placing &
at the end of the expression. The long way is by using the Function
function.
To map a function, f
, to a list of values, list
, one can use the Map
function or the short syntax f /@ list
.
My solution was the following:
similarityScore =
Total[leftList * (Count[rightList, #]& /@ leftList)]
The resulting similarity score was 20,351,745.