Skip to content

Instantly share code, notes, and snippets.

@ambergkim
Created July 19, 2018 18:26
Show Gist options
  • Save ambergkim/0add831613ae1ecc7365ea91bc264c78 to your computer and use it in GitHub Desktop.
Save ambergkim/0add831613ae1ecc7365ea91bc264c78 to your computer and use it in GitHub Desktop.
get neighbor coordinates from 4 sides and 4 corners
class Grid {
constructor(rows, columns) {
this.rows = rows;
this.columns = columns;
}
getNeighbors(row, column) {
let neighbors = [];
if (!this.isValidCoord(row, column)) {
return undefined;
}
let top = this.getTop(row, column);
let topRight = this.getTopRight(row, column);
let right = this.getRight(row, column);
let bottomRight = this.getBottomRight(row, column);
let bottom = this.getBottom(row, column);
let bottomLeft = this.getBottomLeft(row, column);
let left = this.getLeft(row, column);
let topLeft = this.getTopLeft(row, column);
if (top) {
neighbors.push(top);
}
if (topRight) {
neighbors.push(topRight);
}
if (right) {
neighbors.push(right);
}
if (bottomRight) {
neighbors.push(bottomRight);
}
if (bottom) {
neighbors.push(bottom);
}
if (bottomLeft) {
neighbors.push(bottomLeft);
}
if (left) {
neighbors.push(left);
}
if (topLeft) {
neighbors.push(topLeft);
}
return neighbors;
}
getTop(row, column) {
let y = row - 1;
let x = column;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getTopRight(row, column) {
let y = row - 1;
let x = column + 1;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getRight(row, column) {
let y = row;
let x = column + 1;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getBottomRight(row, column) {
let y = row + 1;
let x = column + 1;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getBottom(row, column) {
let y = row + 1;
let x = column;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getBottomLeft(row, column) {
let y = row + 1;
let x = column - 1;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getLeft(row, column) {
let y = row;
let x = column - 1;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
getTopLeft(row, column) {
let y = row - 1;
let x = column - 1;
if (this.isValidCoord(y, x)) {
return [y, x];
}
return undefined;
}
isValidCoord(y, x) {
if (y >= 0 && y < this.rows && x >= 0 && x < this.columns) {
return true;
}
return false;
}
}
let grid1 = new Grid(2, 3);
console.log('grid1 size rows', grid1.rows, 'columns', grid1.columns);
grid1.getNeighbors(5, 3);
// Example Grid
// (0,0) | (0,1) | (0,2) | (0,3)
// ------------------------------
// (1,0) | (1,1) | (1,2) | (1,3)
// ------------------------------
// (2,0) | (2,1) | (2,2) | (2,3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment