# Thread: N while loops into recursion

1. Member
Join Date
Apr 2011
Posts
25
Rep Power
0

## N while loops into recursion

Hi all,

so, i have this list of elements, and what i want to do, is firstly read a number from console,which tells the program how many elements must be excluded from the list, and then print all possible combinations of this modified element list (ElementList.lenght - n). As an example, if i have a list, that contains 7 elements, and user types into the console 2, that means that the program needs to print out all possible combinations of elements, which can be made out of any 5 elements contained in that same list.

I think that it is possible to make it with nested while loops (i wasn't able though), but only for a fixed user input number, so thats why i need to use recursion.

2. Originally Posted by Claymz
Hi all,

so, i have this list of elements, and what i want to do, is firstly read a number from console,which tells the program how many elements must be excluded from the list, and then print all possible combinations of this modified element list (ElementList.lenght - n). As an example, if i have a list, that contains 7 elements, and user types into the console 2, that means that the program needs to print out all possible combinations of elements, which can be made out of any 5 elements contained in that same list.

I think that it is possible to make it with nested while loops (i wasn't able though), but only for a fixed user input number, so thats why i need to use recursion.

You don't need recursion: suppose you have n elements and you want to find all combinations m <= n. e.g. n == 3 and m == 2, so have the element 0, 1 and 2 and you want to list the combinations 01, 02, 12. Given a current combination you can find the next one with this method:

Java Code:
```boolean next(int[] comb, int n) {
for (int i= comb.length; --i >= 0;) {
if (++comb[i] <= n-(comb.length-i)) {
for (; ++i < comb.length; )
comb[i]= comb[i-1]+1;
return true;
}
}
return false;
}```
The method returns true if a next combination could be found and false otherwise. Simply apply this method in a loop while it returns true.

kind regards,

Jos
Last edited by JosAH; 04-17-2011 at 04:08 PM. Reason: darn, my copy and paste failed ... corrected now

#### Posting Permissions

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