【问题标题】:Java Game of life - recursion - user is prompted to enter file name and number of generations to runJava Game of life - 递归 - 提示用户输入文件名和代数运行
【发布时间】:2020-07-15 00:58:40
【问题描述】:

此代码用于生活游戏应用程序。 我的代码提示用户输入容器行和列的文本文件。 文件被读取并输入到二维数组中。 然后将数组传递给我的 nextGeneration 方法,这会打印世代。

我需要根据用户输入将未来数组传递回下一代所需的次数。

我整天都在苦苦思考如何在下一代通过第一代后将“未来”数组传递给它。

任何帮助将不胜感激。谢谢。

static void nextGeneration(int grid[][], int M, int N, int NumberofGenerations) 
{ 
    int[][] future = new int[M][N]; 

    // Loop through every cell 


    for (int l = 1; l < M - 1; l++) 
    { 
        for (int m = 1; m < N - 1; m++) 
            { 
        // finding no Of Neighbours that are alive 
        int aliveNeighbours = 0; 
        for (int i = -1; i <= 1; i++) 
            for (int j = -1; j <= 1; j++) 
            aliveNeighbours += grid[l + i][m + j]; 


        // The cell needs to be subtracted from 
        // its neighbours as it was counted before 
        aliveNeighbours -= grid[l][m]; 

        // Implementing the Rules of Life 

        // Cell is lonely and dies 
        if ((grid[l][m] == 1) && (aliveNeighbours < 2)) 
            future[l][m] = 0; 

        // Cell dies due to over population 
        else if ((grid[l][m] == 1) && (aliveNeighbours > 3)) 
            future[l][m] = 0; 

        // A new cell is born 
        else if ((grid[l][m] == 0) && (aliveNeighbours == 3)) 
            future[l][m] = 1; 

        // Remains the same 
        else
            future[l][m] = grid[l][m]; 

        }

    }


    if (NumberofGenerations != 0)
             {
                return   NumberofGenerations -1 *  nextGeneration(future[l][m], 20, 20,NumberofGenerations -1); 
                // recursive call
            else
                return 1;
             }



    System.out.println("Next Generation"); 
    for (int i = 0; i < M; i++) 
    { 
            for (int j = 0; j < N; j++) 
            { 
                if (future[i][j] == 0) 
                    System.out.print(" "); 
                else
                    System.out.print("*"); 
            } 
            System.out.println(); 
    } 

} 

【问题讨论】:

    标签: java loops recursion


    【解决方案1】:

    一般来说 - 递归是一个好主意,但不利于实现,它通常可以迭代实现,并且比迭代方式花费更多的时间和内存。因此,我将向您展示如何迭代地实现您的算法。

    伪代码:

    1.    Call nextGeneration
    2.    loop 1 to NumberofGenerations
    2.1.    init future
    2.2.    put next generation in future
    2.3.    print future
    2.4.    copy future to grid
    

    由于您的代码创建了下一代,无论未来数组中的内容是什么,它都会起作用。

    你已经有步骤1, 2.1, 2.2, 2.3,你需要做的就是删除你的递归调用,添加一个循环(阶段2.)并将未来复制到网格(阶段2.4)。

    Copy code:

    for (int i=0; i < grid.length; i++)
      for (int j=0; j < grid[i].length; j++)
        grid[i][j] = future[i][j];
    

    【讨论】:

    • 我非常感谢 Yoniff。效果很好。
    • 很高兴你这样做!您可以投票或批准答案:)
    猜你喜欢
    • 2023-04-01
    • 2012-04-15
    • 2022-12-26
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多