
Day 4, part 1
Day 4 challenge of the mighty Advent of Code 2024
Introduction
Welcome to day 4 of Advent of Code. Before we start talking about the today's problem, please read the whole story here. Today, we are presented with a bunch of scratchcards. Each scratchcard has its number, a list of winning numbers and a list of numbers we scratched. We are asked to find how many numbers are winning and calculate the number of points we gain with each scratchcard by starting with one point for one match and doubling the points with each next matching number doubles the amount of points, so for two matching numbers the amount of points is 2 and for 3 matches its 4. Then to get the final answer we need to sum up all the points from every scratchcard.
Understanding the problem
Let's analyze the test data:
1Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
2Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
3Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
4Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
5Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
6Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11Here we can see three parts building each game data (from left to right):
- card number
- winning numbers list
- after the
|we have a list of our numbers
We need to transform this data into something more useful. Then we have to find how many matches each card has. Based on the count of winning numbers we can calculate the points for each card and finally add them together to get the final result.
Looking at the test data we get the following points for each game:
1Game 1: 4 matches = 8 points
2Game 2: 2 matches = 2 points
3Game 3: 2 matches = 2 points
4Game 4: 1 match = 1 point
5Game 5: no matches = 0 points
6Game 6: no matches = 0 pointsCreating files for the challenge
We are going to start by creating the new directory day-4 in or project's root directory.
We also create new main.js file inside the day-4 folder, which will be our main entry for the code for this puzzle.
We can also put the test input data.
1const input = `Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
2Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
3Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
4Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
5Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
6Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11`;Solution
Parsing games data
To parse the cards data from the text, we need to break down the task into few steps:
- Break the block of input data into lines.
- Split each line into game name which includes the game
idand the game data. - Split the game data into winning and our numbers.
- Turn the string containing written numbers into array of numbers. The code that can do so looks like below.
1function textToCards(text) {
2 const lines = textToLinesArray(text);
3 return lines.map(parseCard);
4}
5function textToLinesArray(text) {
6 return text.split('\
7');
8}
9function parseCard(string) {
10 const [gameName, gameData] = string.split(':');
11 return {
12 id: getGameId(gameName),
13 ...getGameData(gameData),
14 };
15}
16function getGameId(gameName) {
17 const [, id] = gameName.split(' ');
18 return parseInt(id);
19}
20function getGameData(gameData) {
21 const [winningNumbersString, ourNumbersString] = gameData.split('|');
22 return {
23 winning: stringToArrayOfNumbers(winningNumbersString),
24 our: stringToArrayOfNumbers(ourNumbersString),
25 };
26}
27function stringToArrayOfNumbers(string) {
28 return string
29 .trim()
30 .split(/\\s+/)
31 .map((numberString) => parseInt(numberString));
32}
33const scratchCards = textToCards(input);
34console.log('Game cards: ', scratchCards);And when we run this piece of code we get:
1Game cards: [
2 {
3 id: 1,
4 winning: [ 41, 48, 83, 86, 17 ],
5 our: [
6 83, 86, 6, 31,
7 17, 9, 48, 53
8 ]
9 },
10 {
11 id: 2,
12 winning: [ 13, 32, 20, 16, 61 ],
13 our: [
14 61, 30, 68, 82,
15 17, 32, 24, 19
16 ]
17 },
18 {
19 id: 3,
20 winning: [ 1, 21, 53, 59, 44 ],
21 our: [
22 69, 82, 63, 72,
23 16, 21, 14, 1
24 ]
25 },
26 {
27 id: 4,
28 winning: [ 41, 92, 73, 84, 69 ],
29 our: [
30 59, 84, 76, 51,
31 58, 5, 54, 83
32 ]
33 },
34 {
35 id: 5,
36 winning: [ 87, 83, 26, 28, 32 ],
37 our: [
38 88, 30, 70, 12,
39 93, 22, 82, 36
40 ]
41 },
42 {
43 id: 6,
44 winning: [ 31, 18, 13, 56, 72 ],
45 our: [
46 74, 77, 10, 23,
47 35, 67, 36, 11
48 ]
49 }
50]Technically we do not need the id, but I decided to add it anyway. Other than that we have all the data in an easy to use format now, so lets commit what we made.
1git add .
2git commit -m "parse game data"Finding number of winning numbers
This should be a fairly simple task. We simply need to loop through our numbers and check it they are present in the list of winning numbers. we return the count of matching numbers as a result.
1function countWinningNumbers(scratchCard) {
2 const { winning, our } = scratchCard;
3 let count = 0;
4 our.forEach((number) => {
5 if (winning.includes(number)) {
6 count++;
7 }
8 });
9 return count;
10}
11const winningCounts = scratchCards.map((scratchCard) => ({
12 id: scratchCard.id,
13 winningCount: countWinningNumbers(scratchCard),
14}));
15console.log('Count of matching numbers: ', winningCounts);The code gives us an array like this:
1Count of matching numbers: [
2 { id: 1, winningCount: 4 },
3 { id: 2, winningCount: 2 },
4 { id: 3, winningCount: 2 },
5 { id: 4, winningCount: 1 },
6 { id: 5, winningCount: 0 },
7 { id: 6, winningCount: 0 }
8]This matches our analysis we did in the introduction. we can now commit the changes and move forward.
1git add .
2git commit -m "count matching numbers"Calculating points for each game
If we think about how we are calculating the points we can see that it is a 2 to the power of matches - 1 or in case of no matches we return 0.
1function calculatePoints(countsOfMatches) {
2 if (countsOfMatches === 0) {
3 return 0;
4 }
5 return Math.pow(2, countsOfMatches - 1);
6}
7const points = winningCounts.map((scratchCard) => ({
8 id: scratchCard.id,
9 points: calculatePoints(scratchCard.winningCount),
10}));
11console.log('Scrach cards points: ', points);Here are the results:
1Scrach cards points: [
2 { id: 1, points: 8 },
3 { id: 2, points: 2 },
4 { id: 3, points: 2 },
5 { id: 4, points: 1 },
6 { id: 5, points: 0 },
7 { id: 6, points: 0 }
8]And this is still matching what we have calculated manually.
We can also calculate the sum of the points.
1const pointsSum = points.reduce((sum, point) => sum + point.points, 0);
2console.log('Sum of the points: ', pointsSum);This gives us the final result which confirms that our calculations are correct.
1Sum of the points: 13Now we can save our work.
1git add .
2git commit -m "calculate scratchcard points"Final result
The great moment has come, it is time to run our code on the real input data. As we did in all our previous challenges, we will use readFile function. We replace input from being the hard-coded test data to be read from file.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');Running the whole code we have prints this message in the terminal:
1Sum of the points: 23750Now we can submit the result. Are we correct?
YES!
We can now commit the final version of our little program.
1git add .
2git commit -m "day 4 part 1 final result"Congratulations to all of you who solved the puzzle together with me. Now its time to beat the part two. See you all in Day 4, part 2!