I want to generate all the subsets of size k from a set.
eg:-say I have a set of 6 elements, I have to list all the subsets in which the cardinality of elements is 3
My old code gives the following result:
111000
110100
110010
110001
101100
101010
101001
100110
100101
100011
011100
011010
011001
010110
010101
010011
001110
001101
001011
000111
Enough optimized:
#include
int firstPermutation(int n, int k) {
return ((1 << k) - 1) << (n - k);
}
int shiftLast1(int a) {
return (a - 1) ^ ((a^(a - 1)) >> 2);
}
int add1AfterLast1(int a) {
return a | (((a^(a - 1)) + 1) >> 2);
}
int nextPermutation(int a) {
if ((a & (a + 1)) == 0) {
return 0;
}
if (a & 1) {
return add1AfterLast1(nextPermutation(a >> 1) << 1);
}
else {
return shiftLast1(a);
}
}
int main() {
int n = 6;
int k = 3;
int a = firstPermutation(n, k);
do {
for (int i = 0; i < n; i++) {
std::cout << ((a >> (n - 1 - i)) & 1);
}
std::cout << std::endl;
} while ((a = nextPermutation(a)));
}