Last active
February 20, 2020 00:53
-
-
Save rgruesbeck/778789bd249d2c840b3de308da9c7a55 to your computer and use it in GitHub Desktop.
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
// Matrix with a strided array | |
class Matrix { | |
constructor (rows, cols) { | |
this.rows = rows; | |
this.cols = cols; | |
this.data = Array(rows * cols).fill(null); | |
} | |
get(x, y) { | |
return this.data[x + y * this.cols]; | |
} | |
set(x, y, val) { | |
this.data[x + y * this.cols] = val; | |
} | |
neighbors(row, col) { | |
// translate offsets and return neighbor cells | |
return [ | |
[0, -1], | |
[0, 1], | |
[1, 1], | |
[1, -1], | |
[-1, 1], | |
[-1, -1], | |
[1, 0], | |
[-1, 0] | |
].map(coords => { | |
return this.get(row + coords[0], col + coords[1]); | |
}) | |
} | |
} | |
let grid = new Matrix(4, 5); | |
grid.set(0, 0, "asteroid"); | |
grid.set(1, 2, "ship"); | |
grid.set(0, 2, "asteroid"); | |
console.log(grid.get(1, 1), grid.data); | |
console.log(grid.neighbors(1, 3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment