Skip to content

Instantly share code, notes, and snippets.

@vyuvalv
Last active November 23, 2020 11:06
Show Gist options
  • Save vyuvalv/08fcd39f90af5ff5e8d7860427ed474d to your computer and use it in GitHub Desktop.
Save vyuvalv/08fcd39f90af5ff5e8d7860427ed474d to your computer and use it in GitHub Desktop.
countNeighbours Cells -
// Edges should be handle differently as they won't have 8 cells serrounding them
// Grid Corners will have 3 neighbours only
// Rows and Columns Edges will have only 5 neighbours
// All Other cells will have 8 neighbours
// Iterate between -1 to 2 will allow to go to each neighbour cell from all sides
countNeighbours(grid, currentColumn, currentRow, lastColumn, lastRow) {
// Getting iterators positions relative to this current column and row
const { xStart, xEnd, yStart, yEnd } = this.getNeighbourhoodCells(currentColumn, currentRow, lastColumn, lastRow);
// Build our neighbourhood array
let neighbourhood = [];
for (let i = xStart; i < xEnd; i++) {
for (let j = yStart; j < yEnd; j++) {
// Skip the current cell
if (i === 0 && j === 0) {
continue;
}
// Shift the grid column and row based on our iterator
neighbourhood.push(grid[i + currentColumn][j + currentRow]);
}
}
// Sum all neighbourhood values in the array
return neighbourhood.reduce((a, b) => a + b, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment