Lessons · JavaScript · grids (a list of lists)
A grid is an array of arrays
grid[row][col]. The outer array holds rows, so the first bracket picks a row and the second picks a cell in it.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Images, boards, spreadsheets, maps. Once the two brackets and the bounds check are automatic, every grid problem is the same two loops with different work in the middle.
How to think about it
Write the two loops first, over grid.length and grid[0].length, and name them rows and cols. Then the work for one cell. Neighbours last, and never without a bounds check.
Worked example
const grid = [[3, 1, 4], [1, 5, 9], [2, 6, 5]];Three rows, three columns.
const rows = grid.length, cols = grid[0].length;Rows is the outer length; columns is one row's length.
console.log(rows, cols, grid[2][0]);3 3 2
let total = 0;
for (let r = 0; r < rows; r++) {Every row. for (let c = 0; c < cols; c++) {Every column of that row.total += grid[r][c];The work, for one cell.
}
}
console.log(total);36
const near = [];Cells touching the top-left one.
for (const [dr, dc] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) {Up, down, left, right.const r = 0 + dr, c = 0 + dc;
if (r >= 0 && r < rows && c >= 0 && c < cols) near.push(grid[r][c]);The bounds check, before the read, always.
}
console.log(near.join(','));1,1Your turn
Guard the read so an off-grid neighbour is skipped.
if (r >= 0 && r < grid.length && c >= 0 && ) {
look(grid[r][c]);
}Solve one with the tests running
The trap
grid[-1] is undefined in JavaScript, so the next bracket throws 'cannot read properties of undefined' several lines away from the missing check.