Last active
March 4, 2019 17:18
-
-
Save ambergkim/715784619015e094cee5b978a3ce8d79 to your computer and use it in GitHub Desktop.
Using offsets. More dry. https://repl.it/@ambergkim/nearestneighbors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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