生活游戏,配置稳定

时间:2019-01-07 15:27:28

标签: c

我需要显示经过多少步或生成之后,我的细胞矩阵才稳定(它重复其配置)。我已经有了nr_neirborhood函数,该函数可以计算单元格近邻关系,而初始化函数可以从输入文件中动态地定位矩阵。我真的很感谢您的帮助。

我试图将实际的单元矩阵与第一个单元矩阵进行比较,看看它们是否相等。但是我发现我的实际矩阵可以与先前的矩阵相同,而不仅仅是第一个矩阵。我该如何记忆所有先前的矩阵?

void obtion_stabile(int **matrix, FILE *p_in, FILE *p_out, int steps) {
    int N, M, buff[1024];
    char ch; //character for enter
    fscanf(p_in, "%d", &N); fscanf(p_in, "%d", &M); //read dimension of the matrix 

    fscanf(p_in, "%c", &ch); //read the enter
    matrice = initialization(matrice, N, M, p_in); //allocate dinamically the matrix from the input file
    int **copy = NULL; copy = alocare(matrice, N, M); //copy is the first matrix, the one read from the file
    int **next = NULL; next = alocare(next, N, M); //next is the matrix where I memorize if a cell live in the next generation or it dies, it depends on the number of the neiborhood
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++)
            copy[i][j] = matrix[i][j];
    }
    int ok = 1; //variable that verify if the actual matrix is equal to the first one
    for (int k = 0; k < steps; k++) {
         for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                int neirborhood = 0; //for each cell I calculate its neiborhood
                neirborhood = nr_neirborhood(matrix, i, j, N, M);
                switch (neirborhood)
                {
                case 2:
                    next[i][j] = matrice[i][j]; //it is the same
                    break;

                case 3:
                    next[i][j] = 1;//it is alive
                    break;

                default:
                    next[i][j] = 0;//it dies
                    break;
                }
            }
         }
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++)
                matrice[i][j] = next[i][j];//after each generation matrix becomes the next one
        }
        if (egality(matrice, copie, N, M)) {
            fprintf(p_out, "Configuration stabile at steps: %d\n", k + 1);
            show(copie, N, M, p_out); ok = 1; 
            break;
        }
        else
            ok = 0;
    }
    if (ok == 0) {
        fprintf(p_out, "there is no stable conifiguration\n"); 
        show(matrice, N, M, p_out);
    }
}

0 个答案:

没有答案