I have a bool [,] board that stores if the cell is alive or dead. The code I have provided is correctly telling me the total neighbors for each cell, the problem is I need to only count the alive neighbors. My thought was to have a check in the
if (WithinBounds (row, col) ) {
if (board[row, col] == true)
liveNeighbor ;
These are my two relevant methods for calculating total neighbors.
private int TotalLiveNeighbors(int x, int y)
{
int liveNeighbors = 0;
for (int row = x - 1; row <= x 1; row )
{
for (int col = y - 1; col <= y 1; col )
{
if (! (row == x && col == y))
{
if (WithinBounds(row, col)) {
liveNeighbors ;
}
}
}
}
return liveNeighbors;
}
public bool WithinBounds(int x, int y)
{
if (x < 0 || y < 0)
return false;
if (x >= 3 || y >= 3)
return false;
return true;
}
I was also working on a different approach that used an offset as so:
int[,] neighborLocations = { { -1,-1 }, { -1,0 }, { -1, 1 },
{ 0, -1}, { 0, 1 },
{ 1, -1}, { 1, 0 }, { 1, 1 } };
int countAliveNeighbors (int x, int y) {
int count = 0;
foreach (int[] offset in neighborLocations) {
if (board.hasAliveNeighborsAt(x offset[1], y offset[0])
count ;
}
return count;
}
Not really sure if this would be more efficient than my first approach
CodePudding user response:
assuming that the array is called 'alive'
if (alive[row,col] && WithinBounds(row, col))