此方法检查单元格是否是边缘单元格(在边界上),然后计算它有多少个活动的邻居。然后返回该值并用于确定该单元是生存还是死亡。这需要很大的空间,看起来很难看。有没有一种方法可以让我用更少的台词来完成这一切?
// takes in board and checks a cell's neighbors, returning the number of living neighbors
// checks if a cell is on a border, therefore causing it to have less neigbors
public static int checkNeighbors(int[][] board, int i, int j)
{
int count = 0; // live neighbors of cell will be added here
if(i - 1 < 0 && j - 1 < 0) // in top left corner, only three neighbors
{
if(board[i][j + 1] == 1)
count++;
if(board[i + 1][j] == 1)
count++;
if(board[i + 1][j + 1] == 1)
count++;
}
else if(i - 1 < 0 && j + 1 > width - 1) // in top right corner, only three neighbors
{
if(board[i][j - 1] == 1)
count++;
if(board[i + 1][j] == 1)
count++;
if(board[i + 1][j - 1] == 1)
count++;
}
else if(i + 1 > height - 1 && j - 1 < 0) // in bottom left corner, only three neighbors
{
if(board[i][j + 1] == 1)
count++;
if(board[i - 1][j] == 1)
count++;
if(board[i - 1][j + 1] == 1)
count++;
}
else if(i + 1 > height - 1 && j + 1 > width - 1) // in bottom right corner, only three neighbors
{
if(board[i][j - 1] == 1)
count++;
if(board[i - 1][j] == 1)
count++;
if(board[i - 1][j - 1] == 1)
count++;
}
else if(j - 1 < 0) // on left border, only five neighbors
{
if(board[i - 1][j] == 1)
count++;
if(board[i - 1][j + 1] == 1)
count++;
if(board[i][j + 1] == 1)
count++;
if(board[i + 1][j + 1] == 1)
count++;
if(board[i + 1][j] == 1)
count++;
}
else if(j + 1 > width - 1) // on right border, only five neighbors
{
if(board[i - 1][j] == 1)
count++;
if(board[i - 1][j - 1] == 1)
count++;
if(board[i][j - 1] == 1)
count++;
if(board[i + 1][j - 1] == 1)
count++;
if(board[i + 1][j] == 1)
count++;
}
else if(i - 1 < 0) // on top border, only five neighbors
{
if(board[i][j - 1] == 1)
count++;
if(board[i - 1][j - 1] == 1)
count++;
if(board[i - 1][j] == 1)
count++;
if(board[i - 1][j + 1] == 1)
count++;
if(board[i][j + 1] == 1)
count++;
}
else if(i + 1 > height - 1) // on bottom border, only five neighbors
{
if(board[i][j - 1] == 1)
count++;
if(board[i + 1][j - 1] == 1)
count++;
if(board[i + 1][j] == 1)
count++;
if(board[i + 1][j + 1] == 1)
count++;
if(board[i][j + 1] == 1)
count++;
}
else // cell is not on any border, has full eight neighbors
{
if(board[i - 1][j - 1] == 1)
count++;
if(board[i - 1][j] == 1)
count++;
if(board[i - 1][j + 1] == 1)
count++;
if(board[i][j - 1] == 1)
count++;
if(board[i][j + 1] == 1)
count++;
if(board[i + 1][j - 1] == 1)
count++;
if(board[i + 1][j] == 1)
count++;
if(board[i + 1][j + 1] == 1)
count++;
}
return count;
}
stackoverflow告诉我添加更多细节,因为我的帖子大部分是代码。我不认为需要更多的细节,所以我在这里键入这个只是为了摆脱这个错误。
3条答案
按热度按时间0aydgbwb1#
您可以将支票移到一个地方:
你可以用流做一些更短的事情,但是如果你不熟悉它们,这就更清楚了。
j2cgzkjk2#
检查索引是否超出范围或等于您的值
i,j
参数,如果是,则跳过它们。否则,请将它们添加到counter
.z3yyvxxp3#
这个怎么样?
这将在当前单元格周围的点上循环。
它测试是同一个单元还是板外的单元。如果不是,并且细胞是活的,它将在计数中加1。
在选项2中,如果它在电路板之外,则取另一侧的数字。