2
Hello, I wonder why I get the Stackoverflow error in this code, but if I add one more condition in the recursive method, that is if(list.contains(Numb)) I don’t get this error.
(This code would be to verify how many numbers exist in base 3 respecting the condition that from one digit D1 to one digit D2 there is the relation |D2-D1|<=2)
public static int recursive(int base,int numb,ArrayList<Integer> lista){
inst=inst+1;
if(numb<0 || numb>base-1) return 0;
ArrayList<Integer> newArray=new ArrayList<Integer>(lista.size()+1);
for(int i=0;i<lista.size();i++)
newArray.add(lista.get(i));
newArray.add(numb);
cont++;
recursive(base,numb-2,newArray);
recursive(base,numb-1,newArray);
recursive(base,numb+1,newArray);
recursive(base,numb+2,newArray);
return cont;
}
public static void main(String[] args){
ArrayList<Integer> test=new ArrayList(11);
int base=3;
for(int i=1;i<11;i++){
recursive(base,i,test);
}
System.out.println("Numeros validos "+ cont);
System.out.println("Numero de instruções:"+inst);
}
I got it!! Stackoverflow’s definition I already knew, but I was not understanding why this was happening. Now I’m trying to imagine a way to end the loop, the number may contain repeated digits, but the Arraylist cannot be bigger than the base, I tried to add if(list.size()>base) Return 0; but it didn’t work =/
– Geovane Wickert