-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11b.js
107 lines (89 loc) · 2.94 KB
/
11b.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function solve(input) {
const matrix = input.split('\n').map(l => l.trim().split('').map(n => parseInt(n)));
let flashCounter = 0;
for(let step = 0; step < 1000; step++) {
//console.log("in", matrix.map(x => x.join("")).join("\n"));
var flashes = [];
for(let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
matrix[i][j] += 1;
if(matrix[i][j] > 9) {
flashes.push([i, j]);
flashCounter++;
}
}
}
while(flashes.length > 0) {
var point = flashes.pop();
let i = point[0];
let j = point[1];
// Are we along the top edge?
if(i != 0) {
if(j != 0) {
if(increaseNeighbor(matrix, i-1, j-1, flashes)) {
flashCounter++;
};
}
if(j != matrix[i].length - 1) {
if(increaseNeighbor(matrix, i-1, j+1, flashes)){
flashCounter++;
}
}
if(increaseNeighbor(matrix, i-1, j, flashes)){
flashCounter++;
}
}
// Are we along the bottom edge?
if(i != matrix.length - 1) {
if(j != 0) {
if(increaseNeighbor(matrix, i+1, j-1, flashes)){
flashCounter++;
}
}
if(j != matrix[i].length - 1) {
if(increaseNeighbor(matrix, i+1, j+1, flashes)){
flashCounter++;
}
}
if(increaseNeighbor(matrix, i+1, j, flashes)){
flashCounter++;
}
}
// Are we along the left edge?
if(j != 0) {
if(increaseNeighbor(matrix, i, j-1, flashes)){
flashCounter++;
}
}
// Are we along the right edge?
if(j != matrix[i].length - 1) {
if(increaseNeighbor(matrix, i, j+1, flashes)){
flashCounter++;
}
}
}
for(let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if(matrix[i][j] > 9 || matrix[i][j] < 0) {
matrix[i][j] = 0;
}
}
}
//console.log("Return!");
}
return flashCounter;
}
function increaseNeighbor(matrix, m, n, points) {
if(matrix[m][n] < 0 || matrix[m][n] > 9) {
// Already large, let's reset.
matrix[m][n] = -1;
return false;
}
matrix[m][n] += 1;
if(matrix[m][n] > 9) {
points.push([m, n]);
return true;
}
return false;
}
module.exports = solve;