Conway's Game of Life, counting neighbors [closed]

断了今生、忘了曾经 提交于 2019-12-02 22:06:11

问题


I have an error somewhere in my code, I think I am entering an infinite loop. Basically I get a matrix and two indexes, i,j, and i need to count how many neighbors around [i][j] have a value of 1 or 2.

this is my code:

int number_of_living_neighbors(matrix mat,int i, int j, int n,int m)
{
    int counter=0,row_index=0,column_index=0;
    for(row_index=i-1;row_index<=i+1;row_index++)
    {
        for(column_index=j-1;column_index=j+1;column_index++)
        {
            if((row_index>=0)&&(row_index<n)&&(column_index>=0)&&(column_index<m))
            {
                if((mat[row_index][column_index]==1)||(mat[row_index][column_index]==2))
                    counter++;
                if((row_index==i)&&(column_index==j)&&(mat[i][j]==1))
                    counter--;
            }
        }
    }
    printf("The number of living neighbors is %d", counter);
    return counter;
}

it doesnt print anything. mat is the matrix i get, i,j are the pointers, n is number of rows, m is number of columns.


回答1:


for(column_index = j-1 ; column_index = j+1; column_index++)

Your condition contains an assignment, not a comparison. You probably want to use <= instead of =:

for(column_index = j-1 ; column_index <= j+1; column_index++)


来源:https://stackoverflow.com/questions/14171466/conways-game-of-life-counting-neighbors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!