Skip to content

2022 - Day 1 - Counting Calories

Posted on:December 1, 2022 at 03:00 PM

In the spirit of holiday programming, we tackled an Advent of Code challenge that required us to count calories—magical ones! This post will explore the problem, our solution, and the thought process behind it.

Table of Contents

Open Table of Contents

Challenge Overview

Santa’s reindeer need a boost of magical energy from star fruits, and it’s our job to calculate the calorie content of the Elves’ inventory. We need to find out which Elf is carrying the most calories and then sum up the calories carried by the top three Elves.

Our Solution

We approached this problem with JavaScript, focusing on clean and efficient code. Here’s the solution step-by-step:

  1. Read input data from a file using Node.js’s fs module.
  2. Transform this data into a more manageable structure—a list of Elves’ calorie counts.
  3. Sum up the calories for each Elf, sort them, and grab the top three.
  4. Finally, we calculate the total for a festive output.
const fs = require("fs");
const FILE_PATH = "./input.txt";
const input = fs.readFileSync(FILE_PATH, "utf8");

const elves = input
  .trim()
  .split("\n\n")
  .map(elf => elf.split("\n").map(Number))
  .map(elf => elf.reduce((a, b) => a + b))
  .sort((a, b) => b - a)
  .slice(0, 3);

const total = elves.reduce((a, b) => a + b);

console.log(
  `🎄 The most calories available from one elf is ${elves[0].toLocaleString()} calories.`
);
console.log(
  `🎄 The total calories between the top three elves is ${total.toLocaleString()} calories.`
);

Complexity Analysis

The complexity of our solution lies primarily in the sorting step:

Overall, the time complexity is dominated by the sorting step, resulting in O(m log m).

Conclusion

Our JavaScript solution to the calorie counting challenge is both concise and efficient, capable of handling a jolly amount of data with ease. With the magic of programming, we’ve ensured that Santa’s reindeer will be well-fueled this Christmas!

Remember to grab your coding hat along with your Santa hat this season. Happy coding!