
Day 7, part 1
Day 7 challenge of the mighty Advent of Code 2024
Introduction
Let me welcome you to this article where we are going to crack the advent of Code day 7 puzzle. The whole description can be read here. Please do so before moving forward, to have a good context of what we are going to do. Today we are asked to play some cards. We are presented with a list of hands and each hand has a bid. We need to rank these hands by their strength and then to get the final answer we need to multiply each hand's rank by the bid and add all these numbers together.
Understanding the problem
Let's take a look at the test data:
132T3K 765
2T55J5 684
3KK677 28
4KTJJT 220
5QQQJA 483Here we see the left column with hands containing card symbols and the right column with the bids.
A hand consists of five cards labeled one of A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, or 2. The relative strength of each card follows this order, where A is the highest and 2 is the lowest.
Then we determine which type is each of the card hands and we compare them with others to rank them. Based on their ranks, we calculate the final answer by summing up rank * bid of all cards together.
Creating files
We are going to start by creating the new directory day-7 in or project's root directory.
We also create new main.js file inside the day-7 folder, which will be our main entry for the code for this puzzle.
We can also put the test input data inside the main.js.
1const input = `32T3K 765
2T55J5 684
3KK677 28
4KTJJT 220
5QQQJA 483`;Solution
This is what comes to my mind when I think about the steps we need to perform to get the result:
- Parse the input text to create individual hand objects with properties:
cards- array with each card letter/number,bid- the amount of bid.
- Determine what type is the hand (one pair, full house, etc.).
- Rank hands based on hand types and individual cards strengths.
- Multiply each hands
rankandbidand sum them together to get the final answer.
Parse card hands data
To transform the input data into useful objects we simply split the whole input into lines. For each line we take the left column and we slit it into an array of individual characters and the right column is the bid.
1function parseCardHandsFromText(input) {
2 const lines = input.split('\
3');
4 return lines.map(parseCardHand);
5}
6function parseCardHand(string) {
7 const [cards, bid] = string.split(/\\s+/);
8 return { cards: cards.split(''), bid: parseInt(bid) };
9}
10const inputData = parseCardHandsFromText(input);
11console.log('Hands data: ', inputData);We can run the code to see what do we have.
1Hands data: [
2 { cards: [ '3', '2', 'T', '3', 'K' ], bid: 765 },
3 { cards: [ 'T', '5', '5', 'J', '5' ], bid: 684 },
4 { cards: [ 'K', 'K', '6', '7', '7' ], bid: 28 },
5 { cards: [ 'K', 'T', 'J', 'J', 'T' ], bid: 220 },
6 { cards: [ 'Q', 'Q', 'Q', 'J', 'A' ], bid: 483 }
7]This seems to work fine and provide the data in easy to use way. Lets save the changes.
1git add .
2git commit -m "parse card hands data"Find cards hand type
To handle this task we created a lookup object which for each hand type provide some properties:
strength- how strong is the type, based on the strength we can decide which hand of cards is stronger and rank them later on.grouping- describes with a string how the cards in the hand should look like to be of particular type.KK225means the type is two pairs and thegroupingfor this type is221which means we have2cards of one type,2cards of other type and1card of yet another type. If we analyse the test data we know that:32T3Kisone-pair,KK677andKTJJTare bothtwo-pairs,T55J5andQQQJAare boththree-of-kind.
1const cardTypes = {
2 'five-of-kind': { strength: 7, grouping: '5' },
3 'four-of-kind': { strength: 6, grouping: '41' },
4 'full-house': { strength: 5, grouping: '32' },
5 'three-of-kind': { strength: 4, grouping: '311' },
6 'two-pairs': { strength: 3, grouping: '221' },
7 'one-pair': { strength: 2, grouping: '2111' },
8 'high-card': { strength: 1, grouping: '11111' },
9};
10function getCardHandTypes(cardHands, cardTypes) {
11 return cardHands.map((cardHand) => ({
12 ...cardHand,
13 type: getCardHandType(cardHand, cardTypes),
14 }));
15}
16function getCardHandType(cardHand, cardTypes) {
17 const countedCardHand = countCardsInHand(cardHand);
18 return getTypeFromCardCounts(countedCardHand, cardTypes);
19}
20function countCardsInHand(cardHand) {
21 return cardHand.cards.reduce((count, hand) => {
22 if (count[hand]) {
23 count[hand]++;
24 } else {
25 count[hand] = 1;
26 }
27 return count;
28 }, {});
29}
30function getTypeFromCardCounts(cardCounts, cardTypes) {
31 const groupingString = Object.values(cardCounts)
32 .sort((a, b) => b - a)
33 .join('');
34 for (const key in cardTypes) {
35 if (cardTypes[key].grouping === groupingString) {
36 return key;
37 }
38 }
39 throw new Error('no such type');
40}
41const cardHandsWithTypes = getCardHandTypes(inputData, cardTypes);
42console.log('Card hands with types: ', cardHandsWithTypes);As you can see we first take the card hand and count how many card of each kind we have. Then we build this kind of grouping string by taking only the amount of cards, sort them from the highest to lowest and convert into string. Then we compare it with out lookup and this way we can determine which type our hand has. If we run this now, we can see these results:
1Card hands with types: [
2 { cards: [ '3', '2', 'T', '3', 'K' ], bid: 765, type: 'one-pair' },
3 { cards: [ 'T', '5', '5', 'J', '5' ], bid: 684, type: 'three-of-kind' },
4 { cards: [ 'K', 'K', '6', '7', '7' ], bid: 28, type: 'two-pairs' },
5 { cards: [ 'K', 'T', 'J', 'J', 'T' ], bid: 220, type: 'two-pairs' },
6 { cards: [ 'Q', 'Q', 'Q', 'J', 'A' ], bid: 483, type: 'three-of-kind' }
7]This matches our analysis of the test data, so we can save our progress and move forward.
1git add .
2git commit -m "find card hands types"Rank card hands
Now we need to rank these hands. To do so we will follow two rules.
- Comparing the types.
- In case of the same type we compare individual card strengths starting from the left one. Applying these two rules to our test data we get the following ranks:
32T3K- 1,KTJJT- 2,KK677- 3,T55J5- 4 andQQQJA- 5.
1const cardStrengths = {
2 2: 2,
3 3: 3,
4 4: 4,
5 5: 5,
6 6: 6,
7 7: 7,
8 8: 8,
9 9: 9,
10 T: 10,
11 J: 11,
12 Q: 12,
13 K: 13,
14 A: 14,
15};
16function rankCards(cardsWithTypes, cardTypes, cardStrengths) {
17 return cardsWithTypes
18 .sort((prevCard, nextCard) => {
19 if (prevCard.type !== nextCard.type) {
20 return cardTypes[prevCard.type].strength - cardTypes[nextCard.type].strength;
21 }
22 if (prevCard.type === nextCard.type) {
23 for (let i = 0; i < prevCard.cards.length; i++) {
24 if (prevCard.cards[i] !== nextCard.cards[i]) {
25 return cardStrengths[prevCard.cards[i]] - cardStrengths[nextCard.cards[i]];
26 }
27 }
28 return 0;
29 }
30 return 0;
31 })
32 .map((card, idx) => ({ ...card, rank: idx + 1 }));
33}
34const rankedCards = rankCards(cardHandsWithTypes, cardTypes, cardStrengths);
35console.log('Ranked cards: ', rankedCards);We use sort method and we compare elements in this array by type strength and/or by individual cards strength. Then we map the array back to objects. This is the output of our function:
1Ranked cards: [
2 {
3 cards: [ '3', '2', 'T', '3', 'K' ],
4 bid: 765,
5 type: 'one-pair',
6 rank: 1
7 },
8 {
9 cards: [ 'K', 'T', 'J', 'J', 'T' ],
10 bid: 220,
11 type: 'two-pairs',
12 rank: 2
13 },
14 {
15 cards: [ 'K', 'K', '6', '7', '7' ],
16 bid: 28,
17 type: 'two-pairs',
18 rank: 3
19 },
20 {
21 cards: [ 'T', '5', '5', 'J', '5' ],
22 bid: 684,
23 type: 'three-of-kind',
24 rank: 4
25 },
26 {
27 cards: [ 'Q', 'Q', 'Q', 'J', 'A' ],
28 bid: 483,
29 type: 'three-of-kind',
30 rank: 5
31 }
32]This is exactly what we expected so we can commit the changes and go to the final part.
1git add .
2git commit -m "rank card hands"Sum up bids
Now the last thing left is to calculate the final bid by multiplying ranks by bid and add them together. For our test data we have: 765 * 1 + 220 * 2 + 28 * 3 + 684 * 4 + 483 * 5 = 6440. The below code does that for us.
1function getBidsSum(rankedCards) {
2 return rankedCards.reduce((sum, card) => (sum += card.rank * card.bid), 0);
3}
4const sumOfBids = getBidsSum(rankedCards);
5console.log('Sum of bids: ', sumOfBids);And when we run it we get the answer we were looking for.
1Sum of bids: 6440Lets once again save what we did before moving to the final test with real data.
1git add .
2git commit -m "sum up card hand bids"Final result
This is the time to test our code in battle. Once again we will use the readFile function, to get the real input data, which we copy from the Advent of Code website and we put the data inside input.txt file.
1const fs = require('fs');
2function readFile(filename) {
3 return fs.readFileSync(filename, 'ascii');
4}
5const input = readFile('input.txt');Now we run the code and we can see in the terminal:
1Sum of bids: 248453531If we submit the answer we can see:
Great! It looks like we are right once again!
We can save the final result.
1git add .
2git commit -m "day 7 part 1 final result"And I hope to see you in Day 7, part 2!