-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rules.js
91 lines (74 loc) · 3.04 KB
/
Rules.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
// Rules.js
export class Rules {
static applyRules(currentGrid) {
const rows = currentGrid.length;
const columns = currentGrid[0].length;
// Create a copy of the current grid to store the next generation
const nextGrid = [];
const currentTime = new Date().getTime();
// Loop through each cell in the current grid
for (let i = 0; i < rows; i++) {
const newRow = [];
for (let j = 0; j < columns; j++) {
const neighbors = this.countLiveNeighbors(currentGrid, i, j);
const cellValue = currentGrid[i][j];
const lastActiveTime = this.getLastActiveTime(cellValue);
if (cellValue === 1) {
// Live cell
if (neighbors < 2 || neighbors > 3 || this.isInactive(lastActiveTime, currentTime)) {
// Rule 1: Any live cell with fewer than two live neighbors dies,
// Rule 3: Any live cell with more than three live neighbors dies,
// or Rule for inactivity: Mark cell as inactive if it's been inactive for too long
newRow.push(0); // Cell dies
} else {
// Rule 2: Any live cell with two or three live neighbors lives on
newRow.push(1); // Cell lives
}
} else {
// Dead cell
if (neighbors === 3) {
// Rule 4: Any dead cell with exactly three live neighbors becomes a live cell
newRow.push(1); // Cell comes to life
} else {
// Dead cell remains dead
newRow.push(0);
}
}
}
nextGrid.push(newRow);
}
return nextGrid;
}
static countLiveNeighbors(grid, row, col) {
const rows = grid.length;
const columns = grid[0].length;
let count = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
const newRow = (row + i + rows) % rows;
const newCol = (col + j + columns) % columns;
// Check if the neighbor is a live cell
if (grid[newRow][newCol] === 1) {
count++;
}
}
}
// Exclude the cell itself from the count
if (grid[row][col] === 1) {
count--;
}
return count;
}
static getLastActiveTime(cellValue) {
// Retrieve the last active time from the cell value
return cellValue === 1 ? parseInt(cellValue / 10) : null;
}
static isInactive(lastActiveTime, currentTime) {
// Set the threshold for inactivity to 1 minute (in milliseconds)
const inactivityThreshold = 60000;
if (lastActiveTime) {
return currentTime - lastActiveTime > inactivityThreshold;
}
return false;
}
}