【发布时间】: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();
}
}
【问题讨论】: