Advent of Code 2022 - Day 1 Javascript Solution

By Henri Parviainen

Advent of Code Cover image

Advent of Code is here again and it's time to solve some coding puzzles! This year I decided to share my solutions here on the blog. Here is my approach to the first-day problems.

Disclaimer

This solution is not the fastest implementation nor is it claiming to be the best way to solve the problem. There are many ways to solve it and this is just how I did it with Javascript. By sharing I hope it can help someone who is struggling to find a solution to the puzzle.

Solution

To be able to run my solution, you should have same project setup as me.

First, download the input and save it as a txt file in the same directory as you have your javascript file. If you don't yet have a javascript file - make one.

So at the starting point, your folder structure should be:

/
-- index.js
-- input.txt

Part 1 & Part 2

Add the following code to your index.js file.

let fs = require("fs");
const input = fs.readFileSync("./input.txt", "utf-8").toString();

const caloriesPerElfArray = input.split(/\n\n/gi);

let caloriesPerElfCombinedArray = [];

for (let i in caloriesPerElfArray) {
  let currentElfsCaloriesArray = caloriesPerElfArray[i].split(/\n/gi);
  let currentElfsCaloriesCombined = 0;

  currentElfsCaloriesArray.forEach(index => {
    currentElfsCaloriesCombined += +index;
  });

  caloriesPerElfCombinedArray.push(currentElfsCaloriesCombined);
}

caloriesPerElfCombinedArray.sort((a, b) => b - a);

// Answer for part 1 - Calories amount for elf with most calories

console.log(caloriesPerElfCombinedArray[0]);

// Answer for part 2 - Top 3 Elves calories

console.log(
  caloriesPerElfCombinedArray[0] +
    caloriesPerElfCombinedArray[1] +
    caloriesPerElfCombinedArray[2]
);

Run in it with node index.js and you'll have your answers for the first day!

SHARE