Created
July 1, 2020 05:07
-
-
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
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
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