Algorithm to Generate All k Combinations of n Items in C
The task at hand is to create a program that generates and displays all possible combinations of k distinct people from a set of n individuals. This can be achieved using a combination-generating algorithm, which operates as follows:
Algorithm:
For each permutation:
Implementation in C :
#include <algorithm> #include <iostream> #include <string> void comb(int N, int K) { std::string bitmask(K, 1); // K leading 1's bitmask.resize(N, 0); // N-K trailing 0's // print integers and permute bitmask do { for (int i = 0; i < N; ++i) // [0..N-1] integers { if (bitmask[i]) std::cout << " " << i; } std::cout << std::endl; } while (std::prev_permutation(bitmask.begin(), bitmask.end())); } int main() { comb(5, 3); }
Sample Output:
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
The above is the detailed content of How to Generate All k Combinations of n Items in C ?. For more information, please follow other related articles on the PHP Chinese website!