Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterative algorithm for combination generation [duplicate]

Tags:

algorithm

Possible Duplicate:
Algorithm to return all combinations of k elements from n

Is there any iterative algorithm to generate combinations of N numbers taking 'r' at a time ?

like image 989
Mariselvam Avatar asked Jan 30 '11 18:01

Mariselvam


1 Answers

Yes there is.

Here is code from the wrong answer Library.

void generate_combos(int n, int k) {
    int com[100];
    for (int i = 0; i < k; i++) com[i] = i;
    while (com[k - 1] < n) {
        for (int i = 0; i < k; i++)
            cout << com[i] << " ";
        cout << endl;

        int t = k - 1;
        while (t != 0 && com[t] == n - k + t) t--;
        com[t]++;
        for (int i = t + 1; i < k; i++) com[i] = com[i - 1] + 1;
    }
}

This generates the combinations in lexicographic order.

like image 134
Chris Hopman Avatar answered Nov 03 '22 00:11

Chris Hopman