我有一個 bool [,] 板來存盤單元格是活著還是死了。我提供的代碼正確地告訴我每個單元格的鄰居總數,問題是我只需要計算活著的鄰居。我的想法是檢查
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;
}
不確定這是否比我的第一種方法更有效
uj5u.com熱心網友回復:
假設該陣列被稱為“活著”
if (alive[row,col] && WithinBounds(row, col))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474361.html
