How to use array list in a recursive function:(pls help)
-
static ArrayList Permute(int[] a,int start,int finish)) { if(start!=finsh) Permute(a,start+1,finish) } In this recursive function I need to add the int [] a(array) collection to array list and return the array list how can I do that? (simply how to add values to a array list in a recursive function and the return the array list with all values) like ( arraylist alist =new arraylist(); alist .add(1); alist .add(2); then return alist but this wont work in recursive function like above due each time alist get reinitialized
-
static ArrayList Permute(int[] a,int start,int finish)) { if(start!=finsh) Permute(a,start+1,finish) } In this recursive function I need to add the int [] a(array) collection to array list and return the array list how can I do that? (simply how to add values to a array list in a recursive function and the return the array list with all values) like ( arraylist alist =new arraylist(); alist .add(1); alist .add(2); then return alist but this wont work in recursive function like above due each time alist get reinitialized
I think that you don't want to do what you are asking for at all. I think that you want to create the ArrayList once, and use it in the recursive function. Create the ArrayList before you call the recursive function, and pass the reference to the ArrayList as a parameter:
static void Permute(int[] a, int start, int finish, ArrayList results)) {
results.Add(a);
if (start != finish) {
Permute(a, start + 1, finish, results);
}
}--- b { font-weight: normal; }
-
static ArrayList Permute(int[] a,int start,int finish)) { if(start!=finsh) Permute(a,start+1,finish) } In this recursive function I need to add the int [] a(array) collection to array list and return the array list how can I do that? (simply how to add values to a array list in a recursive function and the return the array list with all values) like ( arraylist alist =new arraylist(); alist .add(1); alist .add(2); then return alist but this wont work in recursive function like above due each time alist get reinitialized
Hello Again?!! Why do you insist on making it in a recursive call?? One line of code is enough:
ArrayList MyArrayList = new ArrayList(a);
If you insist, you can check if the ArrayList is already initialized before reinitializing it:
ArrayList alist;
static ArrayList Permute(int[] a, int start, int finish)
{
if(alist.Count == 0)
alist = new ArrayList()
alist.Add(1);
alist.Add(2);
if(start != finish)
Permute(a, start+1, finish)
return alist;
}but I'm sure there is a much better way of doing whatever you are trying to do!! Please post more details about what you are trying to do, perhaps we code suggest a better approach.
Regards:rose: