Skip to content

Instantly share code, notes, and snippets.

@Stormix
Created July 1, 2020 05:07
Show Gist options
  • Save Stormix/9dcb74300284de16da3bca14c3835405 to your computer and use it in GitHub Desktop.
Save Stormix/9dcb74300284de16da3bca14c3835405 to your computer and use it in GitHub Desktop.
Given a 2D matrix (flattened to 1D) and an ID, get the 8 surrounding neighbours
public getNeighbours(idx: number): number[] {
const neighbours: number[] = []
const size = this.rows * this.cols
const w = this.cols
const h = this.rows
const debug = {
cell: idx,
n: -1,
w: -1,
e: -1,
s: -1,
}
if ((idx - w) >= 0) {
neighbours.push(idx - w) // north
debug.n = idx - w
}
if ((idx % w) !== 0) {
neighbours.push(idx - 1) // west
debug.w = idx - 1
}
if (((idx + 1) % w) !== 0) {
neighbours.push(idx + 1) // east
debug.e = idx + 1
}
if (idx + w < size) {
neighbours.push(idx + w) // south
debug.s = idx + w
}
if (((idx - w - 1) >= 0) && (idx % w !== 0)) {
neighbours.push(idx - w - 1) // northwest
}
if (((idx - w + 1) >= 0) && ((idx + 1) % w !== 0)) {
neighbours.push(idx - w + 1) // northeast
}
if (((idx + w - 1) < size) && (idx % w !== 0)) {
neighbours.push(idx + w - 1) // southwest
}
if (((idx + w + 1) < size) && ((idx + 1) % w !== 0)) {
neighbours.push(idx + w + 1) // southeast
}
return neighbours
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment