0

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

3
Contributors
2
Replies
5
Views
6 Years
Discussion Span
Last Post by nezachem
0

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;
}
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.