I want an algorithm to compute all permutations of a fixed size binary number with a given hamming weight. For example, if the hamming weight is 2 and the binary size is 4 t
You can implement the "lexicographically next bit-permutation" using Gosper's Hack:
unsigned int v; // current permutation of bits
unsigned int w; // next permutation of bits
unsigned int t = v | (v - 1); // t gets v's least significant 0 bits set to 1
// Next set to 1 the most significant bit to change,
// set to 0 the least significant ones, and add the necessary 1 bits.
w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));
Or if you don't have ctz
(_BitScanForward
on MSVC),
unsigned int t = (v | (v - 1)) + 1;
w = t | ((((t & -t) / (v & -v)) >> 1) - 1);
You can generate them in the following manner:
Initially, make a vector with n - r zeros in the beginning and r ones in the end(0011
for n = 4 and r = 2).
Then, repeat the following procedure:
0110
, we first move the rightmost one that can be moved to the left and get 1010
, then we shift all ones to the right from it to the end of the vector and get 1001
.This solution has O(C(n, r) * n)
time complexity. One more feature of this solution: it generates elements in lexicographical order.