Hung-Yi's LogoHung-Yi’s Journal

Advent of Code 2022: Day 1

A TypeScript solution for the Advent of Code 2022, Day 1 puzzle: beginning the journey with basic grouping, sorting and summation.

Today’s puzzle asks us to sum up groups of numbers and find the largest N groups.

The puzzle input looks something like this.

1000
2000
3000

4000

5000
6000

We see that a blank line separates the groups of numbers that represent the calorie counts for each elf, so we can total up the calories for each elf by calling reduce over the lines and adding each new number to the last element in the accumulated list, but adding a new element to the end of the accumulated list if there’s a blank line (i.e. a new group total).

const elves: number[] = puzzleInput
  .split('\n')
  .reduce(
    (acc: number[], curr: string) => {
      if (curr === '') {
        // blank line means new group;
        // so start a new total
        acc.push(0);
      } else {
        // add to the previous group
        const prev = acc.length - 1;
        acc[prev] += parseInt(curr);
      }
      return acc;
    },
    [0] // begin with one group
  );

For part 1, we just need the elf with the max total calories.

const part1 = Math.max(...elves);

For part 2, we want the top 3 elves, so we might as well sort the list. We can get the top 3 by using a negative parameter in the slice() function, then add them up with a simple reduce for summation.

const part2 = elves
  .sort((a, b) => a - b)
  .slice(-3)
  .reduce((sum, x) => sum + x, 0);

Final solution

const elves: number[] = puzzleInput
  .split('\n')
  .reduce(
    (acc: number[], curr: string) => {
      if (curr === '') {
        // blank line means new group;
        // so start a new total
        acc.push(0);
      } else {
        // add to the previous group
        const prev = acc.length - 1;
        acc[prev] += parseInt(curr);
      }
      return acc;
    },
    [0] // begin with one group
  );

const part1 = Math.max(...elves);

const part2 = elves
  .sort((a, b) => a - b)
  .slice(-3)
  .reduce((sum, x) => sum + x, 0);

console.log("Part 1:", part1);
console.log("Part 2:", part2);
Part 1: 67658
Part 2: 200158