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