If I want to generate all combinations of a set of numbers 0-max, I can do so with for loops. The following code will output all two-number pairs:

for(unsigned int i = 0; i <= max; i++)
 {
 for(unsigned int j = 0; j <= max; j++)
  {
  cout << i << " " << j << std::endl;
  }
 }

Output:

0 0
0 1
0 2
...
0 max
1 0
1 1
1 2
...
1 max

Say now I want to output all four-number combinations. I could easily nest two more loops. However, now I want to write generic code to do this for any number of N-number combinations. You can no longer use this nested loop structure, because the nested loops are hard coded for a particular N.

Any suggestions on how to do this?

David

Recursion?

This particular problem has an iterative solution as well. Set up an array of N ints, and treat it as a max-base number. The increment function gives you a next combination:

bool increment(int arr[], int N, int max)
{
    int i;
    for(i = 0; (i < N) && ((arr[i] += 1) == max); i++) {
        arr[i] = 0;
    }
    return i < N;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.