-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.ts
43 lines (34 loc) · 1.14 KB
/
part1.ts
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
import * as fs from 'fs';
const [rawNumbers, ...rawBoards] = fs.readFileSync('input', 'utf8').split('\n\n');
type Slot = { marked: boolean; number: number };
const numbers = rawNumbers.split(',').map((n) => Number(n));
const boards = rawBoards.map((board) =>
board.split('\n').map((row) =>
row.trim().split(/\s+/).map((n) => ({ marked: false, number: Number(n) }) as Slot),
),
);
const mark = (board: Slot[][], number: number) => {
board.forEach((row) => row.forEach((slot) => slot.number === number && (slot.marked = true)));
};
const checkWin = (board: Slot[][]) => {
const winnerRow = board.some((row) => row.every((slot) => slot.marked));
const winnerCol = board[0].some((s, i) => board.every((row) => row[i].marked));
return winnerRow || winnerCol;
};
const calcScore = (board: Slot[][]) => {
let sum = 0;
board.forEach((row) => row.forEach((slot) => !slot.marked && (sum += slot.number)));
return sum;
};
const solve = () => {
for (const number of numbers) {
for (const board of boards) {
mark(board, number);
if (checkWin(board)) {
return number * calcScore(board);
}
}
}
};
const result = solve();
console.log(result);