-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle-2.js
57 lines (47 loc) · 1.47 KB
/
puzzle-2.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
const isMarked = (val) => val === "X";
const markNumber = (bingoNumber, card) => {
for (let rowIndex = 0; rowIndex < card.length; rowIndex++) {
const row = card[rowIndex];
for (let colIndex = 0; colIndex < row.length; colIndex++) {
const num = row[colIndex];
if (num === bingoNumber) {
card[rowIndex][colIndex] = "X";
return;
}
}
}
};
const hasBingo = (card) => {
const gridSize = card.length;
for (let index = 0; index < gridSize; index++) {
const isRowBingo = card[index].every(isMarked);
const isColBingo = card.every((row) => isMarked(row[index]));
if (isRowBingo || isColBingo) {
return true;
}
}
return false;
};
const output = (input) => {
const groups = input.split("\n\n");
const bingoNumbers = groups.splice(0, 1)[0].split(",");
let bingoCards = groups.map((card) =>
card.split("\n").map((row) => row.match(/.{1,3}/g).map((num) => num.trim()))
);
for (const bingoNumber of bingoNumbers) {
for (let index = bingoCards.length - 1; index >= 0; index--) {
const bingoCard = bingoCards[index];
markNumber(bingoNumber, bingoCard);
if (hasBingo(bingoCard)) {
bingoCards.splice(index, 1);
if (bingoCards.length === 0) {
const sumOfUnmarked = bingoCard
.flat()
.reduce((acc, cur) => acc + (isMarked(cur) ? 0 : parseInt(cur)), 0);
return sumOfUnmarked * bingoNumber;
}
}
}
}
};
module.exports = output;