← Back View problem

Day 1 — Calorie Counting

Part 1

This one is pretty simple. The first thing we want to do is split the input into groups. We do this by splitting on 2 empty lines.

const output = input.split(/[\n\r]{2,}/g);

Next we’ll go through each group, split them by new linem, filter out any falsey values, and convert the strings to numbers.

const output = input
  .split(/[\n\r]{2,}/g)
  .map((group) => group.split("\n").filter(Boolean).map(Number));

Now that we have multiple groups of numbers, we will use reduce to add them together. We’ll use our handy arraySum utility function to do this.

const output = input
  .split(/[\n\r]{2,}/g)
  .map((group) => group.split("\n").filter(Boolean).map(Number))
  .reduce((totalCals, pack) => {
    totalCals.push(arraySum(pack));

    return totalCals;
  }, []);

Finally we can spread the output to Math.max to find out the largest sum of calories.

return Math.max(...output);

This gives us our final answer of 71,934. 🎉

Part 2

Another quick one! All we need to do is sort our output from highest to lowest, take the first 3 values, and sum them up.

arraySum(output.sort((a, b) => b - a).slice(0, 3));

Here our final answer is 211,447

← Back View problem