目前能够计算总邻居,我只需要活着的邻居
我有一个布尔[,]板,该木板存储,如果细胞还活着或死亡。我提供的代码正确地告诉我每个单元格的总邻居,问题是我只需要计算活着的邻居。我的想法是对这些
if (WithinBounds (row, col) ) {
if (board[row, col] == true)
liveNeighbor++;
是我的两种相关方法来计算总邻居。
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;
}
我还在研究一种使用偏移的不同方法:
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;
}
不确定这是否比我的第一种方法更有效
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设阵列称为“活着”
assuming that the array is called 'alive'