活着的邻居细胞未正确计数

Alive neighbour cells not correctly counted

本文关键字:邻居 细胞 活着      更新时间:2023-10-16

我知道我的标题不是很具体,但这是因为我不知道问题的来源。自2到3个小时以来,我一直遇到这个问题,从理论上讲,一切都应该起作用,但事实并非如此。这件代码:

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {
        neighbour = coords(locX + x, locY + y, width);      //Get the cell index in the array
        if (existsInOrtho(ortho, neighbour)) {      //If the index exists in the array
            if (ortho[neighbour] == 0) {        //Cell is dead
                cnt--;      //Remove one from the number of alive neighbour cells
            }
        } else {        //Cell is not in the zone
            cnt--;      //Remove one from the number of alive neighbour cells
        }
    }
}

遍历所有邻居单元,以在数组中获取其值(1为活着,为0(。"坐标"功能,此处显示:

int coords(int locX, int locY, int width)
{
    int res = -1;
    locX = locX - 1;    //Remove one from both coordinates, since an index    starts at 0 (and the zone starts at (1;1) )
    locY = locY - 1;
    res = locX * width + locY;      //Small calculation to get the index of the pixel in the array
    return res;
}

在数组中获取单元格的索引。但是,当我运行代码时,它不起作用,邻居单元的数量不正确(就像每次附近的人都没有计算一个单元格(。我尝试手动分解所有内容,并且它有效,所以我不知道是什么毁了最终代码中的所有内容...这是完整的代码。抱歉,如果我犯了任何英语错误,那不是我的母语。

此代码...

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {

实际检查 9 单元格。也许您忘记了它检查(x,y(=(0,0(。那将包括细胞本身及其邻居。

一个简单的修复是:

for ( int x = -1; x <= 1; x++ ) {       //Iterate through the 8 neighbour cells plus the one indicated
    for ( int y = -1; y <= 1; y++ ) {
        if (x || y) {

另外,simulate函数(来自您的链接(犯了一个常见的错误,即在处理其旁边的单元格所需的状态更改之前,在同一数组中更新单元格的值。最简单的修复程序是保留两个数组 - 两个网格的两个完整副本(在您的代码中,两个ortho数组(。从Orthoa阅读时,请更新Orthob。然后在下一代,翻转。从Orthob读取并写入Orthoa。