-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfire-hazard2.js
86 lines (70 loc) · 1.79 KB
/
fire-hazard2.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
class Grid {
constructor (x, y) {
this._x = x;
this._y = y;
this._matrix = [];
for (let r = 0; r < y; r++) {
const row = [];
for (let c = 0; c < x; c++) {
row.push(0);
}
this._matrix.push(row);
}
}
_mutateRange (x1, y1, x2, y2, fn) {
for (let r = y1; r <= y2; r++) {
for (let c = x1; c <= x2; c++) {
this._matrix[r][c] = fn(this._matrix[r][c]);
}
}
}
execute (command, x1, y1, x2, y2) {
switch (command) {
case 'turn on':
return this.turnOn(x1, y1, x2, y2);
case 'toggle':
return this.toggle(x1, y1, x2, y2);
case 'turn off':
return this.turnOff(x1, y1, x2, y2);
default:
break;
}
}
turnOn (x1, y1, x2, y2) {
this._mutateRange(x1, y1, x2, y2, (value) => value + 1);
}
toggle (x1, y1, x2, y2) {
this._mutateRange(x1, y1, x2, y2, (value) => value + 2);
}
turnOff (x1, y1, x2, y2) {
this._mutateRange(x1, y1, x2, y2, (value) => {
return value - 1 < 0 ? 0 : value - 1;
});
}
get brightness () {
let level = 0;
for (let r = 0; r < this._y; r++) {
for (let c = 0; c < this._x; c++) {
level += this._matrix[r][c];
}
}
return level;
}
}
const setupLights = (input, x = 1000, y = 1000) => {
const grid = new Grid(x, y);
input
.split('\n')
.map((instruction) => instruction.trim())
.forEach((instruction) => {
const parts = instruction.match(/(.*)\s(\d+),(\d+)\sthrough\s(\d+),(\d+)/);
const command = parts[1];
const x1 = parseInt(parts[2]);
const y1 = parseInt(parts[3]);
const x2 = parseInt(parts[4]);
const y2 = parseInt(parts[5]);
grid.execute(command, x1, y1, x2, y2);
});
return grid.brightness;
};
module.exports = setupLights;