ARTICLE AD BOX
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 relative_neighbors_positions[][] = { { -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 relative_position[] : relative_neighbors_positions ) { int nb_x = x + relative_position[ 0 ]; int nb_y = y + relative_position[ 1 ]; if( isInRange( nb_x ) && isInRange( nb_y ) && cells[ nb_x ][ 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.
