-
Notifications
You must be signed in to change notification settings - Fork 0
/
Board.js
71 lines (60 loc) · 1.35 KB
/
Board.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
class Board {
constructor(input) {
this.value = input.split('\n').map((row) =>
row
.trim()
.replace(/\s\s/g, ' ')
.split(' ')
.map((value) => ({
value: parseInt(value, 10),
marked: false,
}))
);
this._lastMarkedCell = null;
}
get isWinning() {
for (let i = 0; i < 5; i++) {
const row = this.value[i];
const col = this.value.map((row) => row[i]);
if (row.every((cell) => cell.marked) || col.every((cell) => cell.marked))
return true;
}
return false;
}
get lastMarked() {
if (!this._lastMarkedCell) {
return null;
}
const [i, j] = this._lastMarkedCell;
return this.value[i][j].value;
}
get score() {
const lastMarked = this.lastMarked;
if (!this.isWinning || !lastMarked) {
return 0;
}
return (
this.value.reduce(
(score, row) =>
score +
row.reduce(
(rowScore, cell) => rowScore + (cell.marked ? 0 : cell.value),
0
),
0
) * lastMarked
);
}
mark(number) {
this.value.forEach((row, i) =>
row.forEach((cell, j) => {
if (cell.value === number) {
cell.marked = true;
this._lastMarkedCell = [i, j];
}
})
);
return this.isWinning;
}
}
export default Board;