-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavascript.js
More file actions
55 lines (55 loc) · 1.48 KB
/
Javascript.js
File metadata and controls
55 lines (55 loc) · 1.48 KB
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
var inputs = readline().split(" ");
const width = parseInt(inputs[0]);
const height = parseInt(inputs[1]);
let grid = [];
for (let i = 0; i < height; i++) {
const line = readline();
grid.push(line.split(""));
}
let _grid = [];
// We initialize a new table that will contain the updated grid
for (let i = 0; i < height; i++) {
_grid.push([]);
for (let j = 0; j < width; j++) {
_grid[i].push("?");
}
}
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
let count = 0;
// We look at the neighboring values to the cell
if (i - 1 >= 0 && grid[i - 1][j] == 1) {
count++;
}
if (i - 1 >= 0 && j - 1 >= 0 && grid[i - 1][j - 1] == 1) {
count++;
}
if (i - 1 >= 0 && j + 1 < width && grid[i - 1][j + 1] == 1) {
count++;
}
if (i + 1 < height && grid[i + 1][j] == 1) {
count++;
}
if (i + 1 < height && j - 1 >= 0 && grid[i + 1][j - 1] == 1) {
count++;
} // and count the number of alive
if (i + 1 < height && j + 1 < width && grid[i + 1][j + 1] == 1) {
count++;
}
if (j - 1 >= 0 && grid[i][j - 1] == 1) {
count++;
}
if (j + 1 < width && grid[i][j + 1] == 1) {
count++;
}
// We proceed to the update according to the defined rules
if ((count === 3 && grid[i][j] == 0) || (count >= 2 && count <= 3 && grid[i][j] == 1)) {
_grid[i][j] = 1;
} else {
_grid[i][j] = 0;
}
}
}
for (let i = 0; i < _grid.length; i++) {
console.log(_grid[i].join(""));
}