-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday4.js
72 lines (60 loc) · 1.73 KB
/
day4.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
60
61
62
63
64
65
66
67
68
69
70
71
72
const fs = require('fs');
const assert = require('assert');
const rawData = fs.readFileSync('./data/day4.txt', 'utf8').split('\n');
const numbers = rawData
.splice(0, 1)[0]
.split(',')
.map((item) => parseInt(item));
const boards = new Map();
const winningScores = [];
const calledNumbers = numbers.splice(0, 5);
const filteredData = rawData.filter((line) => line.length > 0);
function generateBoards() {
let iteration = 0;
while (filteredData.length >= 5) {
const rows = filteredData.splice(0, 5);
const board = rows.map((row) => {
return row
.split(' ')
.filter((item) => item.length > 0)
.map((item) => parseInt(item));
});
boards.set(iteration, board);
iteration++;
}
}
function sumUnMarkedNumbers(board) {
return board.reduce((acc, row) => {
row.forEach((square) => {
if (!calledNumbers.includes(square)) {
acc += square;
}
});
return acc;
}, 0);
}
function checkForWinners() {
boards.forEach((board, key) => {
const columns = [];
for (let i = 0; i < 5; i++) {
columns.push(board.map((row) => row[i]));
}
for (var row of [...board, ...columns]) {
if (row.every((item) => calledNumbers.includes(item))) {
// sumOfUnMarkedNumbers = sumUnMarkedNumbers(board);
winningScores.push(sumUnMarkedNumbers(board) * calledNumbers.at(-1));
//Don't check anymore rows on this board
boards.delete(key);
break;
}
}
});
if (numbers.length && boards.size) {
calledNumbers.push(numbers.splice(0, 1)[0]);
return checkForWinners();
}
}
generateBoards(filteredData);
checkForWinners();
console.log(`part1answer: ${winningScores[0]}`);
console.log(`part2answer: ${winningScores.at(-1)}`);