Question Details

No question body available.

Tags

java conways-game-of-life

Answers (2)

April 17, 2026 Score: 1 Rep: 249 Quality: Low Completeness: 50%

Instead of subtracting 1, just skip the center cell explicitly:

public int getNeighbors(int x, int y) {
    int neighbors = 0;

for (int i = -1; i = 0 && nx < cells[0].length && ny < cells.length) { neighbors += cells[ny][nx]; } } }

return neighbors; }
April 17, 2026 Score: 0 Rep: 1,253 Quality: Low Completeness: 60%

First, let’s establish that we need getNeighbors(), since the rules to be applied are based on how many “live” neighbors each cell has that’s exactly what we want to obtain, anything else is noise (since the nextCellGen() handles the rest of the operation), so all we need to do is traverse the neighboring locations and count how many are “alive,” and we can do this with the following approach (which isn’t the only one, and certainly not the best):

int relativeneighborspositions[][] = {
   { -1, -1 },
   {  0, -1 },
   {  1, -1 },
   { -1,  0 }, 
   {  1,  0 },
   { -1,  1 },
   {  0,  1 },
   {  1,  1 }
};

// we verify that the position is indeed within the // boundaries of the... “universe” // I'm assuming that “cells” has the same number of // rows and columns booleam isInRange( int x ) { return x >= 0 && x < cells.length; }

public int getNeighbors( int x, int y ) { int neighbors = 0; for( int relativeposition[] : relativeneighborspositions ) { int nbx = x + relativeposition[ 0 ]; int nby = y + relativeposition[ 1 ]; if( isInRange( nbx ) && isInRange( nby ) && cells[ nbx ][ nb_y == 1 ) neighbors++; } return neighbors; }

Note: You could omit the isInRange() method and even the two lines preceding the if statement, but I prefer more verbose code that is easier to read.