I am trying to find / create a two-circle algorithm that generates all permutations of K-bit-count 1in the bit mask N-bit-count, where K < N. The number of permutations (N choose K) = N!/(K!(N-K)!).
These two algorithms, starting with the Twiddling Hacks bit , are close.
unsigned int v;
unsigned int w;
unsigned int t = v | (v - 1);
w = (t + 1) | (((~t & -~t) - 1) >> (trailingZeroCount(v) + 1));
Similarly.
unsigned int v;
unsigned int w;
unsigned int t = (v | (v - 1)) + 1;
w = t | ((((t & -t) / (v & -v)) >> 1) - 1);
These algorithms generate permutations in lexicographic order that I do not need. However, I need an algorithm that includes a bitmask m.
unsigned int m;
unsigned int v;
unsigned int w;
...
source
share