Search code examples
c++conways-game-of-life

Counting neighboring cells for Conway's Game of Life in C++


I am trying to write a count neighbor method for Conway's game of life. If a dead cell is neighbored by 2 or 3 living cells, it should come alive. However, my code is not correctly counting all the neighbors. If i give the input coordinates (10, 10), (10, 11), (10, 12) which would produce

   ***

the program will print the next generation as

    *
    *

with coordinates at (10, 11) and (11, 11). However, there should also be a point at (9,11). I know that the problem occurs in this function and that for point (9,11) the function is not counting 3 neighbors.

int Life::neighbor_count (int row, int col)
{
  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];//increase the count is neighbor is alive
    }
  }
  count -=grid [row][col];//reduce count, since cell is not its own neighbor
  return count;
}

Solution

  • As @AlexD pointed out, i<row+1 should be i<=row+1 which would explain your answer.