-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturn01.js
62 lines (55 loc) · 1.29 KB
/
turn01.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
const crypto = require('crypto');
const W = 8, H = 8;
function gen() {
const buf = crypto.randomBytes(W * H);
var world = [], x = 0;
for (var i = 0; i < H; i++) {
world[i] = [];
for (var j = 0; j < W; j++) {
world[i][j] = buf[x++] % 2;
}
}
return world;
}
function out(world) {
var buf = '';
for (var i = 0; i < H; i++) {
for (var j = 0; j < W; j++) {
buf += (world[i][j] ? '*' : ' ') + ' ';
}
buf += '\n';
}
console.log(buf);
}
function run(world) {
for (var i = 0; i < H; i++) {
for (var j = 0; j < W; j++) {
world[i][j] = runLife(world, i, j);
}
}
}
function runLife(world, i, j) {
var living = world[i][j];
var lifes = lifeCountRound(world, i, j);
if (lifes < 2 && lifes > 3) {
living = 0;
} else if (lifes == 3) {
living = living ? 0 : 1;
}
return living;
}
function lifeCountRound(world, i, j) {
var n = 0;
for (var y = Math.max(0, i - 1); y < Math.min(i + 1, H); y++) {
for (var x = Math.max(0, j - 1); x < Math.min(j + 1, W); x++) {
if (!(x == i && y == j)) {
n += world[y][x];
}
}
}
return n;
}
var world = gen();
out(world);
run(world);
out(world);