Cleaner solution using neighbours cordinates in array
function nextGeneration(grid) { var neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]]; return grid.map((r, ri) => r.map((c, ci) => { if (ri !== 0 && ci !== 0 && ri < grid.length - 1 && ci < r.length - 1) { let neighboursCount = neighboursCords .reduce((s, v) => s += grid[ri + v[0]][ci + v[1]], 0); return 0 + (neighboursCount === 3 || (c === 1 && neighboursCount === 2)); } return 0; }) ); }
- function nextGeneration(grid) {
return grid.map((row, rowIndex) => {return row.map((cell, colIndex) => {if (rowIndex !== 0 && colIndex !== 0 && rowIndex < grid.length - 1 && colIndex < row.length - 1) {let neighboursCount = grid[rowIndex][colIndex + 1] +grid[rowIndex][colIndex - 1] +grid[rowIndex + 1][colIndex + 1] +grid[rowIndex + 1][colIndex] +grid[rowIndex + 1][colIndex - 1] +grid[rowIndex - 1][colIndex + 1] +grid[rowIndex - 1][colIndex] +grid[rowIndex - 1][colIndex - 1];return 0 + (neighboursCount === 3 || (cell === 1 && neighboursCount === 2));- var neighboursCords = [[0, 1], [0, -1], [1, 1], [1, 0], [1, -1], [-1, 1], [-1, 0], [-1, -1]];
- return grid.map((r, ri) =>
- r.map((c, ci) => {
- if (ri !== 0 && ci !== 0 && ri < grid.length - 1 && ci < r.length - 1) {
- let neighboursCount = neighboursCords
- .reduce((s, v) => s += grid[ri + v[0]][ci + v[1]], 0);
- return 0 + (neighboursCount === 3 || (c === 1 && neighboursCount === 2));
- }
- return 0;
});});- })
- );
- }