-
Notifications
You must be signed in to change notification settings - Fork 0
/
turn02.js
66 lines (60 loc) · 1.33 KB
/
turn02.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
function gen(h, w, src) {
var x = 0;
var world = [];
for (var i = 0; i < h; i++) {
world[i] = [];
for (var j = 0; j < w; j++) {
world[i][j] = src ? src[x++] % 2 : -1;
}
}
return world;
}
function out(world, h, w) {
var s = '';
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
s += (world[i][j] ? '·' : ' ') + ' ';
}
s += '\n';
}
console.log(s);
}
function runLife(life, roundCount) {
if (roundCount < 2 || roundCount > 3) {
return 0;
}
if (roundCount == 3) {
return life ? 0 : 1;
}
return life;
}
function roundOf(h, w, i, j) {
var y1 = Math.max(i - 1, 0),
y2 = Math.min(i + 1, h);
var x1 = Math.max(j - 1, 0),
x2 = Math.min(j + 1, w);
return { i, j, y1, y2, x1, x2 };
}
function countRound(world, round) {
var n = 0;
for (var y = round.y1; y <= round.y2; y++) {
for (var x = round.x1; x <= round.x2; x++) {
if (!(y === round.i && x === round.j)) {
n += world[y][x];
}
}
}
return n;
}
function run(world, h, w) {
var newWorld = gen(h, w);
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
var life = world[i][j];
var rcnt = countRound(world, h, w, i, j);
newWorld[i][j] = runLife(life, rcnt);
}
}
return newWorld;
}
module.exports = { gen, out, runLife, roundOf, countRound, run };