N selects K bit permutation with bit mask

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; // current permutation of bits where bitCount(v) == K
unsigned int w; // next permutation where bitCount(w) == bitCount(v)

unsigned int t = v | (v - 1);
w = (t + 1) | (((~t & -~t) - 1) >> (trailingZeroCount(v) + 1)); 

Similarly.

unsigned int v; // current permutation of bits where bitCount(v) == K
unsigned int w; // next permutation where bitCount(w) == bitCount(v)

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; // bitmask from which next permutation is chosen
                // where bitCount(m) == N
unsigned int v; // current permutation of bits where (v & m) == v
                // and bitCount(v) == K
unsigned int w; // next permutation of bits where (w & m) == w
                // and bitCount(w) == bitCount(v)
...
+4
source share
1 answer

- CPU, ​​ PEXT Intel Haswell, , -, . , , , . .

+1

All Articles