-
Notifications
You must be signed in to change notification settings - Fork 0
/
1.js
88 lines (67 loc) · 2.5 KB
/
1.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
import input from "./input.js";
class BingoMatrix {
matrix = null
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 = {
winningDrawnNumber: null,
winningMatrix: null,
}
constructor (upcomingNumbers, rawBingoMatrices) {
this.upcomingNumbers = upcomingNumbers
this.bingoMatrices = rawBingoMatrices.map(matrix => new BingoMatrix(matrix))
}
play = () => {
this.upcomingNumbers.some(drawnNumber => {
this.bingoMatrices.some(matrix => {
matrix.highlightDrawnNumber(drawnNumber)
if (!matrix.isWinning()) {
return false
}
this.result.winningMatrix = matrix
this.result.winningDrawnNumber = drawnNumber
return true
})
return null !== this.result.winningMatrix
})
const nonHighlightedSum = this.result.winningMatrix.matrix
.reduce((previous, current) => previous.concat(current.filter(number => false === number.highlighted)), [])
.reduce((previous, current) => previous + current.value, 0)
return this.result.winningDrawnNumber * nonHighlightedSum
}
}
const game = new BingoWithSquid(input.upcomingNumbers, input.bingoMatrices)
const output = game.play()
console.log({
title: 'Giant Squid [4.1]',
url: 'https://adventofcode.com/2021/day/4',
upcomingNumbersSampleInput: input.upcomingNumbers.slice(0, 5),
bingoMatrixSampleInput: input.bingoMatrices[0],
output,
})