
previous

page 4
next
Neighbours
For each cell, we'll need to count its neighbours. In this example the cell at row r and column c has 3 neighbours.
My neat idea is to simply add up the numbers for the surrounding 3 x 3 grid.
0+1+0+0+1+0+1+1+0=4
But this includes the cell itself so we must subtract its value: 4-1=3
So we'll need the familar row,column to id function as well.
more for functions.js
function neighbours(r,c) {
var n=0;
for (var row=r-1; row<r+2; row++) {
for (var col=c-1; col<c+2; col++) {
var id=rc2id(row,col);
n+=g_squares[id];
}
}
id=rc2id(r,c);
n-=g_squares[id];
return n;
}
function rc2id(r,c) {
return r*40+c;
}
var n=0;
for (var row=r-1; row<r+2; row++) {
for (var col=c-1; col<c+2; col++) {
var id=rc2id(row,col);
n+=g_squares[id];
}
}
id=rc2id(r,c);
n-=g_squares[id];
return n;
}
function rc2id(r,c) {
return r*40+c;
}
Did you notice that this function will fail badly for edge cells?
previous
next