Workshop › Conway's Game of Life › Step 14 of 32
At the edges a glider crashes and turns into a block. We make the world wrap around instead: the column after the
last one is the first, the row above the top is the bottom. The % (remainder) operator does it.
```js
// Live neighbours among the 8 around (r, c). The edges wrap around, so the world has no border.
function countNeighbors(r, c) {
let count = 0
for (let dr = -1; dr <= 1; dr++) {
for (let dc = -1; dc <= 1; dc++) {
if (dr === 0 && dc === 0) continue
count += grid[(r + dr + ROWS) % ROWS][(c + dc + COLS) % COLS]
}
}
return count
}
```a % b is the remainder of a / b: 60 % 60 is 0, so column 60 becomes column 0.-1 % 60 is still -1 in JavaScript, so we add COLS first: (-1 + 60) % 60 is 59, the last column. When it
is not needed it does no harm: (5 + 60) % 60 is 5.In countNeighbors, replace the lines const nr, const nc and the long if with the single wrapping line, and
update the comment above the function.
Skills: Arrays and objects
← Show the generation Count the living →