c - 在生命游戏矩阵中搜索人口最多的区域

标签 c search conways-game-of-life

我用 C 语言编写了一个生命游戏,它运行得很好,唯一的问题是游戏板比可以显示的大得多。我知道监视器可以显示的行数和列数,并且我认为遵循该操作(搜索人口最多的区域)将是一个好主意。因此,我编写了一个小函数来接收我应该显示的字段部分的四个角的索引,但不知何故,代码似乎给出了随机部分,有时显然是错误的,即活细胞的计算值(最大值)是完全错误的(有时甚至比整个矩阵本身还要大)。这是代码:

int* most_populated_area(int m, int n, bool a[m][n], int r, int c){
    int * rr=malloc(sizeof(int)*4); //return value
    rr[0]=0;
    rr[1]=r;
    rr[2]=0;
    rr[3]=c; //we first assume that the most populated arrea is upper left corner
    int summe=0;
    int max=0; //to controll wheater or not we found a more populated area we need a summe and the max we founded until now
    for(int isearch=0; isearch<m; isearch++){ //we search the matrix row for row
        for(int jsearch=0; jsearch<n; jsearch++){ // and column for column
            for(int ik=0; ik<=r; ik++){ // now from the current flied we go as many rows we are allowed
                for(int jl=0; jl<=c; jl++){ //and also as many columns we are allowed to go
                    int iks=isearch+ik; //we looking on the field is 0 to r
                    int jls=jsearch+jl; //and 0 to c flieds away from our current field
                    if(iks>=m){ //if the field is outside the matrix we have to go back  
                        iks%=r; // iks is clearly bigger than r (because m bigger than r) but iks%r can be r-1 at most,
                        //so we have the rest from iks through r over the edge 
                    }
                    if(jls>=n){ //analog to iks
                        jls%=c;
                    }
                    summe+=a[iks][jls];
                }
            }
            if(summe>max){// the summe is greater than the max we found a more populated area and we save the the results
                max=summe;
                rr[0]=isearch;
                rr[1]=(isearch+r>=m)?(isearch+r)%r:isearch+r;
                rr[2]=jsearch;
                rr[3]=(jsearch+c>=n)?(jsearch+c)%c:jsearch+c;
            }
            summe=0; //anyway we reset the summe to search accurate
        }
    }
    printf("Lifing in this area %d \n", max);
    return rr;
}

最佳答案

有一个近似解,即 O(n)。

将板分成 x 和 y 部分,并搜索最多的 X 和 Y 值。然后将它们设置为要显示的中点(针对边缘进行调整)。

关于c - 在生命游戏矩阵中搜索人口最多的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686774/

相关文章:

c - 为什么我的程序会读取一个额外的结构?

c - 生命游戏.exe 奇怪的输出

c - 如何从可执行文件中查找源文件名?

c++ - 在命令行上使用 Visual Studio 进行编译时如何包含库?

c - 在http请求中记录xml内容

c - 查找是否存在任何 i 以便 array[i] 等于 i 的算法

php - 使用 Elasticsearch 在 Laravel 中搜索查询背后的逻辑

zend-framework - 如何通过多词搜索进行查询自动完成/建议?

Java - Jtable - 具有不同颜色的单元格

python - 生命游戏 - 覆盖当前一代而不是更新到下一代