Skip to content

Instantly share code, notes, and snippets.

@ambergkim
Last active March 4, 2019 17:18
Show Gist options
  • Save ambergkim/715784619015e094cee5b978a3ce8d79 to your computer and use it in GitHub Desktop.
Save ambergkim/715784619015e094cee5b978a3ce8d79 to your computer and use it in GitHub Desktop.
class Grid {
// determine number of rows and columns.
constructor(rows, columns) {
this.rows = rows;
this.columns = columns;
}
// get the neighbors helper
getNeighbors(row, column) {
// check if source is valid.
let isValid = this.isValidCoord(row, column);
// if it's not valid.
if (!isValid) {
return undefined;
}
// offsets relative to the coordinate
let offsets = [
[-1, -1], [-1, 0] , [-1, 1],
[0, -1], [ 0, 1],
[1, -1], [1, 0] , [ 1, 1]
];
let neighbors = offsets
// Add the offsets to the coordinate to get the neighbors.
.map( ([dy, dx]) => [row + dy, column + dx])
// filter out invalid neighbors
.filter( ([y,x]) => this.isValidCoord(y,x));
return neighbors;
}
// verify coordinate validity
isValidCoord(y, x) {
if (y >= 0 && y < this.rows && x >= 0 && x < this.columns) {
return true;
}
return false;
}
}
let grid1 = new Grid(4, 4);
console.log('grid1 size rows', grid1.rows, 'columns', grid1.columns);
let neighbors = grid1.getNeighbors(3, 2);
console.log('neighbors ', neighbors);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment