
Day 2, part 1
Day 2 challenge of the mighty Advent of Code 2024
Introduction
The second day challenge can be found [here](). Read the description carefully to understand the problem we want to solve. Basically we are asked to figure out if in the given games, if the games were "possible". A game is possible if in the given game, the amount cubes in each color doesn't exceed the given maximal of cubes of that color. Each game has an id which is a number and as a solution to this puzzle, we are asked to return the sum of ids of all possible games.
Understanding the problem
Let's take a look at some example data:
1Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
2Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
3Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
4Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
5Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 greenand the example maximal amounts for each color:
1only 12 red cubes, 13 green cubes, and 14 blue cubesSo we take at look at every round in each game and check if none of the colors in each round exceeds the maximal amount.
Doing so we can see that games 3 and 4 are impossible because in game 3 in first round we have 20 red cubes and in game 4 in second round we have 15 blue cubes. All the other games are possible.
So now summing up the ids of all the possible games we get 8 which is the expected result.
Creating files for the challenge
We are going to start by creating the new directory day-1 in our advent-of-code-2023 project's folder.
In the day-1 directory lets add a new main.js file which will be our main entry for the code for this puzzle.
We can already also place our test data in the input variable.
1const input = `Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
2Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
3Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
4Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
5Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green`;Solution
Preparing the input data
To begin, we first need to read the given data and split it into lines, to separate games from each other. To do so lets reuse the textToLinesArray function from Day 1, part 1#Preparing the input data
1function textToLinesArray(text) {
2 return text.split('\
3');
4}
5const inputLines = textToLinesArray(input);
6console.log('Array of strings: ', inputLines);Running this will result in following log in the terminal:
1Array of strings: [
2 'Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green',
3 'Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue',
4 'Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red',
5 'Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red',
6 'Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green'
7]Parsing the game data
As we now have data for each game stored in a separate string in the array, we can take these strings one by one and parse them so we can easily reuse them later.
1function parseGamesData(string) {
2 const [gameName, gameData] = string.split(':');
3 const gameId = getGameId(gameName);
4 return { id: gameId, data };
5}
6function getGameId(gameName) {
7 return parseInt(gameName.replace('Game ', ''));
8}
9const parsedGameData = parseGame(inputLines[1]);
10console.log('The first parsed game: ', parsedGameData);The given piece of code return this result:
1The first parsed game: {
2 id: 1,
3 data: ' 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green'
4}for now we just split the game into its gameName and gameData. The gameName could be easily used to extract the game id, the game data was for now left as the rest of the spited game string. Now we can start thinking how to extract the data from the string and turn it into array of object describing amount of each color in each round of the game.
1function parseGamesData(string) {
2 const [gameName, gameData] = string.split(':');
3 const gameId = getGameId(gameName);
4 return { id: gameId, data: parseGameData(gameData) };
5}
6function getGameId(gameName) {
7 return parseInt(gameName.replace('Game ', ''));
8}
9function parseGameData(gameData) {
10 const separatedGameDataStrings = gameData.trim().split(';');
11 const separatedGameData = separatedGameDataStrings.map(parseRoundData);
12 return separatedGameData;
13}
14function parseRoundData(roundData) {
15 let result = { red: 0, green: 0, blue: 0 };
16 const colorStrings = roundData.split(',').map((line) => line.trim());
17 colorStrings.forEach((colorString) => {
18 const [amount, color] = colorString.split(' ');
19 result[color] = parseInt(amount);
20 });
21 return result;
22}
23const parsedGameData = parseGame(inputLines[1]);
24console.log('The first parsed game: ', parsedGameData);And running this piece of code now, we are getting:
1The first parsed game: {
2 id: 1,
3 data: [
4 { red: 4, green: 0, blue: 3 },
5 { red: 1, green: 2, blue: 6 },
6 { red: 0, green: 2, blue: 0 }
7 ]
8}I think this is the time we can commit our progress before we move forward.
1git add .
2git commit -m "parse input data"Check if game is possible
Now having the data parsed, lets figure out if a given game was possible (none of the colors in the given rounds exceeds the maximal amount). We can achieve this with these couple of functions:
1const maxAmounts = { red: 12, green: 13, blue: 14 };
2function checkIfGameIsPossible(game) {
3 const { data: rounds } = game;
4 return rounds.every(checkIfRoundPossible);
5}
6function checkIfRoundPossible(round) {
7 return Object.entries(round).every(([color, amount]) => maxAmounts[color] >= amount);
8}
9console.log('Is the first game possible?: ', checkIfGameIsPossible(parsedGameData));Let's check this out now.
1Is the first game possible?: trueNow we can do a little bit of clean up so we can check out the results for the whole test data. The whole code so far after the changes looks like this:
1const input = `Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
2Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
3Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
4Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
5Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green`;
6function sumIdsOfPossibleGames(text) {
7 const inputLines = textToLinesArray(text);
8 const parsedGamesData = inputLines.map(parseGame);
9 const gamesPossibilities = parsedGamesData.map((gameData) => ({
10 id: gameData.id,
11 possible: checkIfGameIsPossible(gameData),
12 }));
13 return gamesPossibilities;
14}
15function textToLinesArray(text) {
16 return text.split('\
17');
18}
19function parseGame(string) {
20 const [gameName, gameData] = string.split(':');
21 const gameId = getGameId(gameName);
22 return { id: gameId, data: parseGameData(gameData) };
23}
24function getGameId(gameName) {
25 return parseInt(gameName.replace('Game ', ''));
26}
27function parseGameData(gameData) {
28 const separatedGameDataStrings = gameData.trim().split(';');
29 return separatedGameDataStrings.map(parseRoundData);
30}
31function parseRoundData(roundData) {
32 let result = { red: 0, green: 0, blue: 0 };
33 const colorStrings = roundData.split(',').map((line) => line.trim());
34 colorStrings.forEach((colorString) => {
35 const [amount, color] = colorString.split(' ');
36 result[color] = parseInt(amount);
37 });
38 return result;
39}
40const maxAmounts = { red: 12, green: 13, blue: 14 };
41function checkIfGameIsPossible(game) {
42 const { data: rounds } = game;
43 return rounds.every(checkIfRoundPossible);
44}
45function checkIfRoundPossible(round) {
46 return Object.entries(round).every(([color, amount]) => maxAmounts[color] >= amount);
47}
48console.log('Are games possible?: ', sumIdsOfPossibleGames(input));and the result we get is:
1Are games possible?: [
2 { id: 1, possible: true },
3 { id: 2, possible: true },
4 { id: 3, possible: false },
5 { id: 4, possible: false },
6 { id: 5, possible: true }
7]As we can see the results are correct and we commit the changes and happily move to the last step.
1git add .
2git commit -m "check if games are possible"Summing up the possible games ids
Now having the information of which game is possible we can go through that data and add the ids of possible games together. We need to update the sumIdsOfPossibleGames function and the console.log message.
1function sumIdsOfPossibleGames(text) {
2 const inputLines = textToLinesArray(text);
3 const parsedGamesData = inputLines.map(parseGame);
4 const gamesPossibilities = parsedGamesData.map((gameData) => ({
5 id: gameData.id,
6 possible: checkIfGameIsPossible(gameData),
7 }));
8 return gamesPossibilities.reduce((acc, curr) => {
9 if (curr.possible) {
10 acc += curr.id;
11 }
12 return acc;
13 }, 0);
14}
15...
16console.log(
17 "Sum of possible games ids: ",
18 sumIdsOfPossibleGames(input)
19);Lets now run the code and see what do we get.
1Sum of possible games ids: 8This is the result we were expecting. Now we can commit what we have so far before we run the code against the real input data.
1git add .
2git commit -m "sum possible games ids"Real input data
The final step to solve the first part of the day 1 challenge is to use the real input data provided on the day 2 page. I created the input.txt file inside of the day-1 directory and put the data in it. Now it is time to read the input file. This time again we can reuse the readFile function from day 1.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}Final result
Now we can replace the test input data and run our script one last time to get the final answer to the puzzle.
1const input = readFile('input.txt');1Sum of possible games ids: 1853Now we can copy the number we get and paste it in the submit field on the website. Clicking the [Submit] button will give us a resounding congrats, as we did it right!
We are now also able to move forward to the part two of the puzzle.
The final step is to commit our final code.
1git add .
2git commit -m "day 2 part 1 final result"Now allow me to invite you to follow along with the second part. Day 2, part 2