到目前为止,我已经看了这段时间,并重写了三次代码,这就是我所拥有的,也是我所不理解的。
我有一种检查邻里关系的方法,通过各种印刷线和我的运行它,这是有效的。
int getLiveCellCount(Generation *currentGeneration, int i, int j)
{
int liveCellCount = 0;
// check top row
if( i > 0 )
{
if( j > 0 && currentGeneration->generation[i-1][j-1] == 'X' )
{
liveCellCount++;
}
if( currentGeneration->generation[i-1][j] == 'X' )
{
liveCellCount++;
}
if( j < currentCols && currentGeneration->generation[i-1][j+1] == 'X' )
{
liveCellCount++;
}
}
// check mid row
if( j > 0 && currentGeneration->generation[i][j-1] == 'X' )
{
liveCellCount++;
}
if( j < currentCols && currentGeneration->generation[i][j+1] == 'X' )
{
liveCellCount++;
}
// check bottom row
if( i < currentRows )
{
if( j > 0 && universe[i+1][j-1] == 'X' )
{
liveCellCount++;
}
if( currentGeneration->generation[i+1][j] == 'X' )
{
liveCellCount++;
}
if( j < currentCols && currentGeneration->generation[i+1][j+1] == 'X' )
{
liveCellCount++;
}
}
return liveCellCount;
}我有一个细胞生存或死亡的特殊条件,活细胞中含有X,而死细胞是一个空白。
If the cell is alive:
it dies if it has 0, 1, 4 or more living neighbours (starvation), or
it lives if it has 2 or 3 living neighbours (balance).
If the cell is dead:
it springs to life if it has exactly 3 neighbours (procreation).我将代码实现如下:
for( i=0; i<currentRows; i++ )
{
for( j=0; j<currentCols; j++ )
{
int livingCells = 0;
livingCells = getLiveCellCount(currentGeneration, i,j);
if(universe[i][j] == 'X' )
{
if( livingCells == 2 || livingCells == 3 )
{
universe[i][j] = 'X';
}
else
{
universe[i][j] = ' ';
}
}
else
{
if( livingCells == 3 )
{
universe[i][j] = 'X';
}
}
}
}知道universe[][]是一个文件范围变量,我的想法是用这段代码在初始条件下读入universe,这是可行的。我将这个数组复制到一个结构数组中(稍后存储,当前注释掉)。我扫描universe并检查每个单元格在其附近的活的单元格,在此基础上遵循上面的规则,并根据元素逐个编辑universe。我在这里面漏掉了什么?在某个地方,我没有正确地读到一个条件,我看不见它。
我要感谢你们对我的帮助!就像你们中的许多人提到的那样,我忽略了宇宙中每个细胞必须同时更新的小细节!如前所述,我将宇宙的当前状态复制到结构中的2d数组中,并将其存储在数组中供以后使用,使用当前的宇宙快照来计数单元格数,然后编辑宇宙完美地工作!非常感谢!
发布于 2015-06-18 03:05:54
我认为您的代码有两个问题:
*细胞的更换应在同一代进行。
另一种方法是创建一个不同的2d数组,并在那里保存新版本或新一代,然后在完成后复制到前一个版本。这样,你就可以同时改变世世代代了。
发布于 2015-06-18 05:07:40
总体而言,
1)检查相邻单元的状态必须始终检查被检查的单元是否在2D数组的范围内。
2)不能使用相同的数组来更新目标单元的内容,因为这会改变当某个相邻单元成为目标单元时的邻居计数。方法是保留两个2D数组,并在应用了所有更新之后使用指针切换到最新版本。
https://stackoverflow.com/questions/30905622
复制相似问题