I am trying to find/create a bit twiddling algorithm that generates all K
-bit-count permutations of the 1
s 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)
...