-
Notifications
You must be signed in to change notification settings - Fork 0
/
04.js
59 lines (48 loc) · 1.66 KB
/
04.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {matchNumbers, readInput, sum} from '../../../util.js';
const directoryPath = path.dirname(fileURLToPath(import.meta.url));
const input = await readInput(directoryPath);
const cardDataRegex = /Card( +)(\d+):( +)/;
const scratchCards = input
.trim()
.split('\n')
.map(card => {
const cardData = card
.replace(cardDataRegex, '')
.split('|')
.map(data => matchNumbers(data));
const [winningNumbers, placedNumbers] = cardData;
return {
winningNumbers,
placedNumbers,
};
});
let totalPoints = 0;
for (const scratchCard of scratchCards) {
let correctNumbers = 0;
for (const placedNumber of scratchCard.placedNumbers) {
if (scratchCard.winningNumbers.includes(placedNumber)) {
correctNumbers++;
}
}
totalPoints += Math.floor(2 ** (correctNumbers - 1));
}
console.log('The cards are worth points:', totalPoints);
const numberOfEachCard = {};
for (const [index, scratchCard] of scratchCards.entries()) {
const currentGameIndex = index + 1;
numberOfEachCard[currentGameIndex] = numberOfEachCard[currentGameIndex] || 1;
const numberOfCurrentCard = numberOfEachCard[currentGameIndex];
let matchingNumbers = 0;
for (const placedNumber of scratchCard.placedNumbers) {
if (scratchCard.winningNumbers.includes(placedNumber)) {
matchingNumbers++;
const wonCardIndex = currentGameIndex + matchingNumbers;
const currentNumberOfWonCard = numberOfEachCard[wonCardIndex] || 1;
numberOfEachCard[wonCardIndex] = currentNumberOfWonCard + numberOfCurrentCard;
}
}
}
const numberOfCards = sum(Object.values(numberOfEachCard));
console.log('Total scratchcards:', numberOfCards);