4

I am trying to find/create a bit twiddling algorithm that generates all K-bit-count permutations of the 1s in an N-bit-count bitmask where K < N. The number of permutations is (N choose K) = N!/(K!(N-K)!).

These two algorithms, from Bit Twiddling Hacks, 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, which I don't necessarily need. However, I do need an algorithm that incorporates 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)
...
Warren Whipple
  • 1,060
  • 2
  • 9
  • 18

1 Answers1

1

One option is to use a CPU instruction such as PEXT in Intel Haswell and newer to expand the result from the bit twiddling solution you mention to the mask. If you don't have such an instruction available, you'll probably need a loop. I give two possibilities in this answer.

Community
  • 1
  • 1
Falk Hüffner
  • 4,942
  • 19
  • 25