I am trying to write a program that implements Conway's Game of Life on a grid of 20x60 cells. The grid should wrap around so that the left side is connected to the right side and the top is connected to the bottom.
Thus, any cell with position (0, col)
, will have a neighbour at (maxRow, col)
. Any cell with position (row, 0)
will have a neighbour at (row, maxCol)
.
The following function is supposed to count the number of neighbouring cells. It works for coordinates not on the edges, but not for ones that are. For instance, if there are points at (0, 10)
, (0, 11)
, (0, 12)
, and (0, 10)
is passed into the function, it will return a high number as neighbour count instead of 1
. I know that the mod operator %
would be helpful, but I don't understand how to use it.
{
int i, j;
int count = 0;
for (i = row - 1; i <= row + 1; i++)
for (j = col - 1; j <= col + 1; j++)
count += grid[i][j]; }
if (row==maxrow-1 || row==0)
count = count+ grid [(row-(maxrow-1))*-1][col-1]+grid[(row-(maxrow-1))*-1][col]+grid[(row-(maxrow-1))*-1][col+1];
if (col==0 || col==maxcol-1)
count=count +grid[row-1][(col-(maxcol-1))*-1]+grid[row][(col-(maxcol-1))*-1]+grid[row+1][(col-(maxcol-1))*-1];
count -= grid[row][col];
return count;
}