I have an array with a bunch of values (the length of the array can vary):

int a[] = {1, 6, 9, 4, 3, 7, 5};

I want to generate all possible combinations available. The problem is that the size of the subset may vary. The user may for instance say he wants all possible combinations with 3 elements. Another user may want a combination with 5 elements. For instance, the skeleton of the function may look like:

combination* getSubsets ( int numberOfElementsInSubset){



Where combination might be a class/structure to hold a certain subset. A 2dimensionel array could also be used.

Since the size varies, a bunch of inner loops cannot be hard coded. I have thought of a recursive function that may solve the problem, but can't find a way to start.

Any help will be greatly appreciated.

6 Years
Discussion Span
Last Post by goocreations

You should use recursive for this one. It will be much easier to use recursive. The idea is to swap 2 numbers, and then call the function again until you hit the base case (start==(end-1)). If you want to print out the result, you need only 3 arguments in this recursion - array, start index, end index. If you want to get the result out, pass in another array for saving the result in the base case. I have implemented in both JavaScript and Java, but not in C++ (because I implemented this after I graduated --> no more C++ at work).

Edited by Taywin: n/a


If possible, could you please post the Java code. It would really help.
Thank you!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.