
Day 4, part 2
Day 4 challenge of the mighty Advent of Code 2024
Introduction
Welcome to part two of Advent of code day 4 puzzle. This is a continuation of what we have done in Day 4, part 1. I recommend reading that one first before you jump into this one. 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
After successfully counting points for each scratchcard in part 1, now the rules has changed. Now we are not counting points based on the amount of matching numbers, but instead we are making copies of the cards that are below the current card. We copy as many cards as many matches the current card has. For instance, lets take a look at the test data again.
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 11- Card 1 has four matching numbers, so you win one copy each of the next four cards: cards 2, 3, 4, and 5.
- Your original card 2 has two matching numbers, so you win one copy each of cards 3 and 4.
- Your copy of card 2 also wins one copy each of cards 3 and 4.
- Your four instances of card 3 (one original and three copies) have two matching numbers, so you win four copies each of cards 4 and 5.
- Your eight instances of card 4 (one original and seven copies) have one matching number, so you win eight copies of card 5.
- Your fourteen instances of card 5 (one original and thirteen copies) have no matching numbers and win no more cards.
- Your one instance of card 6 (one original) has no matching numbers and wins no more cards.
With all of these, we end up having1copy ofCard 1,2copies ofCard 2,4copies ofCard 3,8copies ofCard 4,14copies ofCard 5and1copy ofCard 6.
To get the final result we are asked to count all the card that we end up having.
Solution
To keep track of all the copies, we need to keep track of how many instances of a card we have. We can start by reusing the data parsing part but for each card we can introduce new property copies and initialize it with 1. Then we can move through the cards, reuse the functions responsible for counting how many matches we have and based on that, we can increment the number of copies below the current card.
At the end we can count all the copies we have to get the answer to this puzzle.
Keep track of copies
Before we start, lets once more use the test data instead of reading the input file.
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`;Here I list some changes we have to make to our functions to keep track of copies number.
1function parseCard(string) {
2 const [gameName, gameData] = string.split(":");
3 return {
4 id: getGameId(gameName),
5+ copies: 1,
6 ...getGameData(gameData),
7 };
8 }1const winningCounts = scratchCards.map((scratchCard) => ({
2 id: scratchCard.id,
3+ copies: scratchCard.copies,
4 winningCount: countWinningNumbers(scratchCard),
5 }));I also found one bug in our getCardId function:
1function getGameId(gameName) {
2- const [, id] = gameName.split(" ");
3+ const [, id] = gameName.split(/\\s+/);
4 return parseInt(id);
5 }One of the console logs we had, now shows us this cards data:
1Count of matching numbers: [
2 { id: 1, copies: 1, winningCount: 4 },
3 { id: 2, copies: 1, winningCount: 2 },
4 { id: 3, copies: 1, winningCount: 2 },
5 { id: 4, copies: 1, winningCount: 1 },
6 { id: 5, copies: 1, winningCount: 0 },
7 { id: 6, copies: 1, winningCount: 0 }
8]We have here all card id, initial amount of copies which we will use in the next steps and the amount of matching numbers for each card.
Copying the cards
How do we handle the copying?
The copies tells us how many copies we need to add to to the cards below.
The winningCount tells us how many cards below the current card have to be copied.
We will be modifying the card objects directly, because in this case it seems to be a little easier.
1function calculateCardCopies(allCards) {
2 allCards.forEach((currenctCard) => copyCardsBelow(currenctCard, winningCounts));
3}
4function copyCardsBelow(scratchCard, allCards) {
5 const { id, copies, winningCount } = scratchCard;
6 const lastId = findMaxIndex(id, winningCount, allCards);
7 updateCopiesCount(id, lastId, copies, allCards);
8}
9function findMaxIndex(id, winningCount, allCards) {
10 const lastIdInDeck = allCards.length;
11 let lastId = id + winningCount;
12 if (lastId >= lastIdInDeck) {
13 lastId = lastIdInDeck;
14 }
15 return lastId;
16}
17function updateCopiesCount(id, lastId, copies, allCards) {
18 for (let i = id + 1; i <= lastId; i++) {
19 const nextCard = allCards.find((c) => c.id === i);
20 nextCard.copies = nextCard.copies + copies;
21 }
22}
23calculateCardCopies(winningCounts);
24console.log('Recalculated card copies: ', winningCounts);The main calculateCardCopies is simply taking all the cards and calls the main updating function copyCardsBelow on each of them. This function finds the last possible id of a card and then goes through the cards below the current card. Each of these cars has its copies parameter updated. We are using the variable winningCards as a parameter when we call the function. If we run this now, that's what we will see:
1Recalculated card copies: [
2 { id: 1, copies: 1, winningCount: 4 },
3 { id: 2, copies: 2, winningCount: 2 },
4 { id: 3, copies: 4, winningCount: 2 },
5 { id: 4, copies: 8, winningCount: 1 },
6 { id: 5, copies: 14, winningCount: 0 },
7 { id: 6, copies: 1, winningCount: 0 }
8]Looks about right. It means we can commit the changes and move to the last step.
1git add .
2git commit -m "calculate card copies"Count how many cards we ended up with
This is pretty simple task right now and can be simply done using reduce method on the array of cards after successful copies update.
1function countCards(allCards) {
2 return allCards.reduce((acc, card) => (acc += card.copies), 0);
3}
4const amountOfAllCards = countCards(winningCounts);
5console.log('Amount of all cards: ', amountOfAllCards);If we run this, the message will be printed in the terminal:
1Amount of all cards: 30If we now check the expected number of cards we calculated manually in the introduction, we can see that this is the answer we were looking for. We can save the changes.
1git add .
2git commit -m "count all cards"Final result
It is time, to finally try our code out on the real input data. Once again we will make a use of readFile function.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');The moment of truth has come.
1Amount of all cards: 13261850After submitting the result, we are greeted once again! That's the right answer!
The final step is to commit our final code.
1git add .
2git commit -m "day 4 part 2 final result"And hopefully see you all in Day 5, part 1!