这个基本思想是,在一个星球上有三种不同的物种,这三种物种中只有两种能够共同生育,结果是物种死于第三物种的两个新物种。出生,例如我们有ab和c,a和b物种聚集在一起,让2 c新成员出生。
就像:1a 1b和1c (对不起语言)
当a和b想要孩子时他们聚在一起但死了但有两个孩子,这些新孩子来自物种c,结果是:
0a 0b和3 c
在这个casie中,我们说星球成功了,c是主要的诡计。但是当我有3a 4b 2c并且我需要看看这三个物种中是否有任何一个能在这个星球上成功。
我认为我可以使用递归解决方案,但我总是得到错误:
Exception in thread "main" java.lang.StackOverflowError
在我尝试使用递归的函数中。
这是我的代码,我知道有些事情是错的,但我不知道是什么。
public class Automata2 {
public static void main(String[] args) {
int N = 2;
while (N <= 14) {
partition(N);
N++;
}
}
public static void partition(int N) {
int n1,n2,n3;
for(n1=0;n1<=N;n1++){
for(n2=0;n2<=N;n2++){
for(n3=0;n3<=N;n3++){
if((n1+n2+n3)==N){
strPlanetA(n1, n2, n3);
}
}
}
}
}
public static void strPlanetA(int a, int b, int c){
int a2 = a, b2 = b, c2 = c;
while (!(a2!=0 && b2==0 && c2==0)) {
a2=a2+2;
b2--;
c2--;
if (a2==a && b2==b && c2==c) {
System.out.println("Not Fail");
}
if (a2!=0 && b2==0 && c2==0) {
System.out.println("Fail in A");
}
strPlanetA(a2, b2, c2);
}
}
}
该分区只是为了让地球上所有人口都可以获得,我需要看看这架飞机是否在一个人口从2到14的星球上成功。
答案 0 :(得分:0)
堆栈溢出错误是无限递归/循环的通常同义词。基本上你的函数strPlanetA
在代码的末尾调用自己,无论之前发生了什么......再次......再次......等等无休止地。您需要一个条件,在验证时,阻止递归调用。
你的代码在推理上基本上是有缺陷的。如果你想编写递归函数,我非常强烈的建议是先做数学运算。你需要在迭代推理中获得最小的直觉。
例如,您有一个双嵌套递归,一个带递归调用,一个带循环。我不明白为什么你会需要这个。你可以完全放弃递归调用。
答案 1 :(得分:0)
基本上我想要实现的目标是,如何改善这一点应该有更好的方法。
public class Automata2 {
/**
* @param args the command line arguments
*/
static int cont = 0;
public static void main(String[] args) {
int N = 2;
while (N <= 14) {
partition(N);
N++;
}
System.out.println("Cantidad de Respuestas= " + cont);
}
public static void partition(int N) {
int n1,n2,n3;
for(n1=0;n1<=N;n1++){
for(n2=0;n2<=N;n2++){
for(n3=0;n3<=N;n3++){
if((n1+n2+n3)==N){
if (strPlanetA(n1, n2, n3) == 1) {
cont++;
System.out.print("A falla en: ");
System.out.print(n1+"-");
System.out.print(n2+"-");
System.out.println(n3);
}
if (strPlanetB(n1, n2, n3) == 1) {
cont++;
System.out.print("B falla en: ");
System.out.print(n1+"-");
System.out.print(n2+"-");
System.out.println(n3);
}
if (strPlanetC(n1, n2, n3) == 1) {
cont++;
System.out.print("C falla en: ");
System.out.print(n1+"-");
System.out.print(n2+"-");
System.out.println(n3);
}
}
}
}
}
}
public static int strPlanetA(int a2, int b2, int c2){
if((a2!=0 && b2==0 && c2==0)||(c2 == b2)){
return 1;
}
if (b2>0 && c2>0) {
a2=a2+2;
b2--;
c2--;
if (a2!=0 && b2==0 && c2==0) {
return 1;
}
else{
strPlanetA(a2, b2, c2);
}
}
return 3;
}
public static int strPlanetB(int a2, int b2, int c2){
if((a2==0 && b2!=0 && c2==0)||(c2 == a2)){
return 1;
}
if (a2>0 && c2>0) {
a2--;
b2=b2+2;
c2--;
if (a2==0 && b2!=0 && c2==0) {
return 1;
}
else{
strPlanetB(a2, b2, c2);
}
}
return 3;
}
public static int strPlanetC(int a2, int b2, int c2){
if((a2==0 && b2==0 && c2!=0)||(a2 == b2)){
return 1;
}
if (a2>0 && b2>0){
a2--;
b2--;
c2=c2+2;
if (a2==0 && b2==0 && c2!=0) {
return 1;
}
else{
return strPlanetC(a2, b2, c2);
}
}
return 3;
}
}
感谢上面推荐的推荐,这完全是一团糟。