此代码适用于生命游戏应用程序。 我的代码提示用户输入文本文件的容器行和列。 该文件被读取并输入到二维数组中。 然后将该数组传递给我的 nextGeneration 方法,并打印生成的代数。
我需要根据用户输入的需要多次将 future 数组传递回下一代。
我一整天都在努力思考如何在下一代数组经过第一代后将“ future ”数组传递给下一代。
任何帮助将不胜感激。谢谢。
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();
}
}
最佳答案
一般来说 - 递归是一个好主意,但不利于实现,它通常可以迭代实现,并且比迭代方式花费更多的时间和内存。因此,我将向您展示如何迭代地实现您的算法。
伪代码:
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
由于您的代码创建了下一代,无论 future 数组中的内容是什么,它都会起作用。
您已经有了步骤1, 2.1, 2.2, 2.3
,您需要做的就是删除递归调用,添加一个循环(阶段2.
)并将 future 复制到网格(阶段 2.4
)。
for (int i=0; i < grid.length; i++)
for (int j=0; j < grid[i].length; j++)
grid[i][j] = future[i][j];
关于Java 生命游戏 - 递归 - 提示用户输入文件名和运行代数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61002022/