gpt4 book ai didi

java - 在 Java 中使用递归

转载 作者:行者123 更新时间:2023-11-30 09:29:44 25 4
gpt4 key购买 nike

我正在研究 Conway 的生命游戏计划。我已经打印出前两代的细胞,但我不能再打印了。所以我决定使用递归来打印多批细胞。我的 NewCells 方法创建了第二代。我想如果我通过返回 NewCells(c) 而不是 c 来重复上述方法,它会打印出不同的结果,但它会一遍又一遍地打印出同一批细胞。

public class Life {

public static boolean[][] NewCells(boolean[][] c)
{
int N = 5;
int o=0;
int p=0;
int livecnt = 0; //keeps track of the alive cells surrounding cell
int store = 0; //amount of surrounding cells for each individual cell
int livestore[] = new int[N*N];


System.out.println("Next Generation");
// Checks for the amount of "*" surrounding (o,p)

for (o=0; o < N; o++)
{
for (p=0; p<N; p++)
{
for (int k=(o-1); k <= o+1; k++)
{

for (int l =(p-1); l <=p+1; l++)
{
if ( k >= 0 && k < N && l >= 0 && l < N) //for the border indexes.
{

if (!(k== o && l==p)) //so livecnt won't include the index being checked.
{
if (c[k][l] == true)
{
livecnt++;
}
}

}

}
}
livestore[store]= livecnt;
livecnt = 0;
store++;
}
}


//Prints the next batch of cells
int counter= 0;
for (int i2 = 0; i2 <N; i2++)
{
for (int j2 = 0; j2 < N; j2++)
{

if (c[i2][j2] == false)
{
if (livestore[counter] ==3)
{
c[i2][j2]=true;
System.out.print("* ");
}
else
System.out.print("- ");
}

else if (c[i2][j2] == true)
{
if (livestore[counter] ==1)
{
c[i2][j2]= false;
System.out.print("- ");
}
else if (livestore[counter] >3)
{
c[i2][j2]= false;
System.out.print("- ");
}

else
System.out.print("* ");
}
counter++;
}
System.out.println();
}

return NewCell(c);
}
/*************************************************************************************************************************************************/
public static void main(String[] args)
{
int N = 5;
boolean[][] b = new boolean[N][N];
double cellmaker = Math.random();

int i = 0;
int j = 0;


int o=0;
int p=0;
int livecnt = 0; //keeps track of the alive cells surrounding cell
int store = 0; //amount of surrounding cells for each individual cell
int livestore[] = new int[N*N];


System.out.println("First Generation:");
// Makes the first batch of cells
for ( i = 0; i < N ; i++)
{

for ( j = 0; j< N; j++)
{
cellmaker = Math.random();


if (cellmaker > 0.5) // * = alive; - = dead
{
b[i][j]=true;

System.out.print( "* ");

}


if (cellmaker < 0.5)
{ b[i][j] = false;


System.out.print("- ");

}

}
System.out.println();

}


boolean[][] newcells = new boolean[N][N];
newcells = NewCells(b);

}

}

最佳答案

我不认为递归对于这个应用程序是个好主意。它会导致 StackOverflowError,因为每一代都会推送另一个调用堆栈帧。该程序使用的递归与迭代相比没有任何优势。

相反,将对 NewCells 的主要方法调用置于循环中。这样,无论堆栈大小如何,您都可以运行任意数量的迭代。

关于java - 在 Java 中使用递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13556723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com