-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.js
91 lines (70 loc) · 2.71 KB
/
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import input from "./input.js";
class BingoMatrix {
matrix = null
hasWon = false
constructor (rawMatrix) {
this.matrix = rawMatrix.map(row => row.map(number => {
return {
value: number,
highlighted: false,
}
}))
}
highlightDrawnNumber = (drawnNumber) => {
this.matrix.forEach(row => row.forEach(number => number.highlighted = true === number.highlighted ? true : drawnNumber === number.value))
}
isWinning = () => {
return !!(this.matrix.some(row => row.length === row.filter(number => number.highlighted).length)
|| this.reverse().some(column => column.length === column.filter(number => number.highlighted).length))
}
reverse = () => {
let reversedMatrix = this.matrix.map(() => [])
for (let i = 0; i < this.matrix.length; i++) {
for (let j = 0; j < this.matrix.length; j++) {
reversedMatrix[j].push(this.matrix[i][j])
}
}
return reversedMatrix
}
}
class BingoWithSquid {
upcomingNumbers = []
bingoMatrices = []
result = {
lastWinningDrawnNumber: null,
lastWinningMatrixNonHighlightedSum: null,
}
constructor (upcomingNumbers, rawBingoMatrices) {
this.upcomingNumbers = upcomingNumbers
this.bingoMatrices = rawBingoMatrices.map(matrix => new BingoMatrix(matrix))
}
play = () => {
this.upcomingNumbers.some(drawnNumber => {
this.bingoMatrices.forEach(matrix => {
if (matrix.hasWon) {
return
}
matrix.highlightDrawnNumber(drawnNumber)
if (!matrix.isWinning()) {
return
}
matrix.hasWon = true
this.result.lastWinningDrawnNumber = drawnNumber
this.result.lastWinningMatrixNonHighlightedSum = matrix.matrix
.reduce((previous, current) => previous.concat(current.filter(number => false === number.highlighted)), [])
.reduce((previous, current) => previous + current.value, 0)
})
return this.bingoMatrices.length === this.bingoMatrices.filter(matrix => matrix.hasWon).length
})
return this.result.lastWinningDrawnNumber * this.result.lastWinningMatrixNonHighlightedSum
}
}
const game = new BingoWithSquid(input.upcomingNumbers, input.bingoMatrices)
const output = game.play()
console.log({
title: 'Giant Squid [4.2]',
url: 'https://adventofcode.com/2021/day/4#part2',
upcomingNumbersSampleInput: input.upcomingNumbers.slice(0, 5),
bingoMatrixSampleInput: input.bingoMatrices[0],
output,
})