Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Recursion problems

1. ## Recursion problems

Hello. I'm not very familiar with recursive programming, and my problem here is that the recursive statements dont seem to be returning properly to an upper layer. While writing out the process on paper I feel this code should be correct, but it isn't working properly. The below method is initially called by an array list with a count equal to its size.

Code:
```public static void powerSets(ArrayList<Integer> array, int count)
{
ArrayList<Integer> temp = array;
if (count == 0)
return;
else
{
for (int i = 0; i <= temp.size(); i++)
{
System.out.println(temp.toString());
temp.remove(i);
powerSets(temp, temp.size());
}
return;
}```
The return looks similar to:
Code:
```[x, y, z]
[y, z]
[z]```
where it removes the first item each time (i = 0) but it never seems to step up properly and advance i to 1. The next lines are intended to be:
Code:
```[y]
[x, z]
[z]
[x]
[x, y]
[y]
[x]```
What am I doing wrong that is keeping recursion from bumping up a layer and incrementing the for loop properly?

• Hi ThetaZero

You are setting the value of i relative to the size of the ArrayList, but you are removing from the array list. I haven't studied your code, but you may want to replace this:

temp.size()

with the count variable.

• Code:
```package temp;
import java.util.ArrayList;
public class Temp {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ArrayList<Integer> something = new ArrayList();
for (int x = 0; x < 10; x++){
}
Temp tmp = new Temp();
tmp.func(something);
}
public ArrayList func(ArrayList temp) {
if (temp.size() > 0) {
for (int y=0; y < temp.size(); y++) {
System.out.print(temp.get(y) + " ");
}
System.out.println();
temp.remove(0);
func(temp);
}
return temp;
}
}

OUTPUT ::

0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
4 5 6 7 8 9
5 6 7 8 9
6 7 8 9
7 8 9
8 9
9```

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•