Question

for homework we have to program Conway's Game of Life in Java. But I have a problem to calculate the number of neighbors correctly.

We have to use a class Cell which represents the cells in our 2 dimensional field. All alive cells should be saved in a LinkedHashSet.

The problem that comes up is that too much possible alive cells are saved and that i got duplicate cells in my population set.

My code to calculate the neighbors and the next generation is:

public void next() {
   generations++;
   // used to save possible alive cells
   Set<Cell> nextGen = new LinkedHashSet<Cell>();
   int col;
   int row;
   int count;
   for( int i = 0; i < grid.length; i++ ) {
      for( int j = 0; j < grid[ 0 ].length; j++ ) {
         grid[ i ][ j ].setNeighbours( 0 );
      }
   }
   for( Cell e : population ) { // calculate number of neighbors
      col = e.getCol();
      row = e.getRow();
      count = 0;

      for( int i = row - 1;
           i >= 0 && i < ( row + 2 ) && i < grid.length;
           i++ )  {
         for( int j = col - 1;
              j >= 0 && j < ( col + 2 ) && j < grid[ 0 ].length;
              j++ ) {
            count = grid[ i ][ j ].getNeighbours() + 1;
            if( i == row && j == col )
            {
               count--;
            }
            grid[ i ][ j ].setNeighbours( count );
            nextGen.add( grid[ i ][ j ] );

         }
      }
   }
   for( Cell e : population )
   { // check if all alive cells stay alive
      switch( e.getNeighbours() )
      {
      case 3:
      break;
      case 2:
      break;
      default:
         e.setAlive( false );
         population.remove( e );
      break;
      }
   }
   // check which cells get alive
   for( Cell e : nextGen ) {
      if( e.getNeighbours() == 3 ) {
         e.setAlive( true );
         population.add( e );
      }
      else if( e.getNeighbours() == 2 ) {
         /* */
      }
      else
      {
         e.setAlive( false );
      }
   }
}
Was it helpful?

Solution

This line doesn't seem correct:

count = grid[i][j].getNeighbours() + 1;

Shouldn't you be counting alive neighbours? Like this:

if (grid[i][j].isAlive()) count++;

You should be counting Cell e's neighbours. So remove this line

grid[i][j].setNeighbours(count);

and add this line after the i, j loops:

e.setNeighbours(count);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top