
Day 2, part 2
Day 2 challenge of the mighty Advent of Code 2024
Introduction
This article is a continuation of the Day 2, part 1, so if you haven't please read that first as we are going to use the code from there. This part of the challenge is available only when you successfully finished the part 1. The second part of the challenge is described under -- Part Two -- section here.
What is the new problem?
Now, we are asked to check in each game, what is the smallest amount of cubes of each color, to make the game possible. Lets take a look at the example data once more.
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 greenWith the new rules, we get the following answers to that question:
1Game 1: 4 red, 2 green, and 6 blue
2Game 2: 1 red, 3 green, and 4 blue
3Game 3: 20 red, 13 green, and 6 blue
4Game 4: 14 red, 3 green, and 15 blue
5Game 5: 6 red, 3 green, and 2 blueThat basically mean, that we have to find out the highest amount of cubes of each color in the game rounds.
Next we are asked, based on the data we get, calculate the power of each set of cubes, which is calculated by multiplying the minimal amounts of cubes to make the game possible.
In our example the powers we get for each game are:
1Game 1: 48
2Game 2: 12
3Game 3: 1560
4Game 4: 630
5Game 5: 36And finally, to get the answer to the second part of this puzzle, we are asked to return the sum of these powers. In our case, the expected answer is 2286.
Solution
Find minimal amount of cubes
Previously we were checking game possibilities by checking if the amounts of cubes in each color are not exceeding the given amounts for each color. This time we are not going to check any possibilities, but instead we need to find out the minimal amounts ourselves based on the cubes in each round in each game.
1function getMinimalCubesToMakeGamePossible(game) {
2 const { data: rounds } = game;
3 return rounds.reduce(
4 (acc, curr) => {
5 Object.entries(curr).forEach(([color, amount]) => {
6 if (amount > acc[color]) {
7 acc[color] = amount;
8 }
9 });
10 return acc;
11 },
12 { red: 0, green: 0, blue: 0 }
13 );
14}In the snippet above, we can see a simple function that takes a game, goes through all rounds and replaces the result for each color if it is higher than the previous result. Now we create a new main function sumOfGamePowers which will for now use the above function. We also want to again, use the test data instead of reading the file.
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 sumOfGamePowers(text) {
7 const inputLines = textToLinesArray(text);
8 const parsedGamesData = inputLines.map(parseGame);
9 const minimalCubesForEachGame = parsedGamesData.map(
10 getMinimalCubesToMakeGamePossible
11 );
12 return minimalCubesForEachGame;
13}
14...
15console.log(
16 "Minimal cubes to make a game possible: ",
17 sumOfGamePowers(input)
18);After running this code now, the following data is being logged in the console:
1Minimal cubes to make a game possible: [
2 { red: 4, green: 2, blue: 6 },
3 { red: 1, green: 3, blue: 4 },
4 { red: 20, green: 13, blue: 6 },
5 { red: 14, green: 3, blue: 15 },
6 { red: 6, green: 3, blue: 2 }
7]And these are the results we expected. Hooray! We can commit the changes.
1git add .
2git commit -m "calculate min cube amounts"Calculating the power factor
Now, when we have the minimal amounts of cubes to make a game possible, we can calculate the power factor for each of them. To do so we simply have to multiply the amount of cubes in each color.
1function calculateGamePower(game) {
2 return game.red * game.green * game.blue;
3}Now lets use this in the main function and see what results do we get.
1function sumOfGamePowers(text) {
2 const inputLines = textToLinesArray(text);
3 const parsedGamesData = inputLines.map(parseGame);
4 const minimalCubesForEachGame = parsedGamesData.map(
5 getMinimalCubesToMakeGamePossible
6 );
7 const gamePowers = minimalCubesForEachGame.map(calculateGamePower);
8 return gamePowers;
9}
10...
11console.log(
12 "Powers of each game: ",
13 sumOfGamePowers(input)
14);1Powers of each game: [ 48, 12, 1560, 630, 36 ]This is the resounding success, we did it! Again, let's commit the changes.
1git add .
2git commit -m "calculate game power"Summing up the powers
The final step to get the answer to this puzzle, is to sum up all the powers. Fortunately this is pretty easy, simply by using reducemethod on the powers array.
1function getSumOfPowers(powers) {
2 return powers.reduce((acc, curr) => (acc += curr), 0);
3}This now can be used in the main function.
1function sumOfGamePowers(text) {
2 const inputLines = textToLinesArray(text);
3 const parsedGamesData = inputLines.map(parseGame);
4 const minimalCubesForEachGame = parsedGamesData.map(
5 getMinimalCubesToMakeGamePossible
6 );
7 const gamePowers = minimalCubesForEachGame.map(calculateGamePower);
8 return getSumOfPowers(gamePowers);
9}
10...
11console.log("Sum of game powers: ", sumOfGamePowers(input));Now the final check can be done. Fingers crossed!
1Sum of game powers: 2286Success! We get the correct answer. Now is the time for a real test of our new program. We need to run it using the real data. But before that, time to save our progress.
1git add .
2git commit -m "calculate game powers sum"Final result
Now we can replace the test data with the data from input.txt. Here is the full code we have which has code for both parts of the day 2 puzzle.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');
6function sumIdsOfPossibleGames(text) {
7 const inputLines = textToLinesArray(text);
8 const parsedGamesData = inputLines.map(parseGame);
9 const gamesPossibilities = parsedGamesData.map(getGamePossibility);
10 return sumPossibleGames(gamesPossibilities);
11}
12function sumOfGamePowers(text) {
13 const inputLines = textToLinesArray(text);
14 const parsedGamesData = inputLines.map(parseGame);
15 const minimalCubesForEachGame = parsedGamesData.map(getMinimalCubesToMakeGamePossible);
16 const gamePowers = minimalCubesForEachGame.map(calculateGamePower);
17 return getSumOfPowers(gamePowers);
18}
19function textToLinesArray(text) {
20 return text.split('\
21');
22}
23function parseGame(string) {
24 const [gameName, gameData] = string.split(':');
25 const gameId = getGameId(gameName);
26 return { id: gameId, data: parseGameData(gameData) };
27}
28function getGameId(gameName) {
29 return parseInt(gameName.replace('Game ', ''));
30}
31function parseGameData(gameData) {
32 const separatedGameDataStrings = gameData.trim().split(';');
33 return separatedGameDataStrings.map(parseRoundData);
34}
35function parseRoundData(roundData) {
36 let result = { red: 0, green: 0, blue: 0 };
37 const colorStrings = roundData.split(',').map((line) => line.trim());
38 colorStrings.forEach((colorString) => {
39 const [amount, color] = colorString.split(' ');
40 result[color] = parseInt(amount);
41 });
42 return result;
43}
44function getMinimalCubesToMakeGamePossible(game) {
45 const { data: rounds } = game;
46 return rounds.reduce(
47 (acc, curr) => {
48 Object.entries(curr).forEach(([color, amount]) => {
49 if (amount > acc[color]) {
50 acc[color] = amount;
51 }
52 });
53 return acc;
54 },
55 { red: 0, green: 0, blue: 0 }
56 );
57}
58const maxAmounts = { red: 12, green: 13, blue: 14 };
59function getGamePossibility(game) {
60 return {
61 id: game.id,
62 possible: checkIfGameIsPossible(game),
63 };
64}
65function checkIfGameIsPossible(game) {
66 const { data: rounds } = game;
67 return rounds.every(checkIfRoundPossible);
68}
69function checkIfRoundPossible(round) {
70 return Object.entries(round).every(([color, amount]) => maxAmounts[color] >= amount);
71}
72function sumPossibleGames(games) {
73 return games.reduce((acc, curr) => {
74 if (curr.possible) {
75 acc += curr.id;
76 }
77 return acc;
78 }, 0);
79}
80function calculateGamePower(game) {
81 return game.red * game.green * game.blue;
82}
83function getSumOfPowers(powers) {
84 return powers.reduce((acc, curr) => (acc += curr), 0);
85}
86console.log('Sum of possible games ids: ', sumIdsOfPossibleGames(input));
87console.log('Sum of game powers: ', sumOfGamePowers(input));Running this will give us logs with answers for both parts, but what we are interested in is:
1Sum of game powers: 72706And after submitting this answer we now now that we produced a piece of a properly working code, as our answer is correct! Congratulations!
The final step is to commit our final code.
1git add .
2git commit -m "day 2 part 2 final result"That was a lot of fun! If you are interested in the next puzzle, please check out Day 3, part 1