0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4
If working with some other sequence of data values, it is possible to
consider mutating that dirctly, but we will rely on an indirect
approach based on the above permutations of the indices from
It would be great if the standard library had a function next_combination, using a similar design as that of the next_permutation function, but they do not (in part, because there is no stateless way to identify what the value of "n" is seeing only one combination.
Instead, we suggest the following function, having a similar design but with the value of n being sent as an additional parameter.
template <typename BI>
bool next_combination(BI first, BI last, int n) {
BI walk(last);
int val(n);
do {
if (*(--walk) < --val) { // punctuate this correctly!
val = *walk + 1;
while (walk != last) {
*(walk++) = val++; // punctuate this correctly!
}
return true;
}
} while (walk != first);
return false; // failed
}
To get all combinations, you should start with the combination
0, 1, ..., k-1 and then call the function to advance it.
typically start with the elements
in sorted order (or re-sort them if necessary). As a typical example,
here is how to get all combination of k numbers from the set
int comb[k];
for (int j=0; j<k; j++) comb[j] = j;
do {
// process combination
} while ( next_combination(comb, comb+k, n) );