Advent of Code 2024: Day 1!
Itβs somehow already December, which means itβs time for the Advent of Code. Iβve been doing this for a few years now, and itβs always a fun way to get back into the swing of writing code after a long break.
Here is my solution for Day 1, which was a simple problem involving sorting and calculating the sum of the absolute differences between two arrays. I honestly still forget how reduce
works every time I use it, so Iβm trying to get better at it by using it more often especially in lil puzzles like this.
Usually Iβd make my life easier and just copy/paste the input into the arrays directly, but decided to just parse the string input this time. Doesnβt really make a difference / need to be in the solution but π€·ββοΈ.
// advent of code 2024 day 1
import {input} from './input';
// `lists` is a 2D array containing two sub-arrays of numbers.
const lists: [number[], number[]] = input
.split('\n') // split the input into lines
.reduce<[number[], number[]]>(
(list, line) => {
const [first, second] = line.trim().split(/\s+/).map(Number); // split by whitespace and parse numbers
list[0].push(first);
list[1].push(second);
return list;
},
[[], []] // initialize the accumulator with two empty arrays
);
// `sortedLists` is created by mapping over `lists` and sorting each sub-array in ascending order.
// the `.sort((a, b) => a - b)` ensures numerical sorting rather than the default order.
const sortedLists = lists.map(list => list.sort((a, b) => a - b));
// `total` calculates the sum of the absolute differences between corresponding elements
// in the two sorted arrays.
// it uses `reduce` to iterate over the first sorted array (`sortedLists[0]`),
// computes the absolute difference with the matching index in the second array (`sortedLists[1][i]`),
// and [acc]umulates the result. the initial value of the accumulator is 0.
const total = sortedLists[0].reduce(
(acc, val, i) => acc + Math.abs(val - sortedLists[1][i]),
0
);
console.log(`π
π DAY 1 ANSWER PART 1: ${total}`);
// similar to the previous solution, but instead of calculating the absolute difference,
// we calculate the 'similarity score', the number of times it appears in the second array.
// we do this by iterating over the first array (no need for the sorted one) and multiplying the current value
// by the number of times it appears in the second array.
const similarityScore = lists[0].reduce((acc, val, i) => {
const count = lists[1].filter((n) => n === val).length; // count the number of times the current value appears in the second list
return acc + val * count;
}, 0); // initialize the accumulator with 0
console.log(`π
π DAY 1 ANSWER PART 2: ${similarityScore}`);
$ bun 01/index.ts
π
π DAY 1 ANSWER PART 1: 2166959
π
π DAY 1 ANSWER PART 2: 23741109