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 then there are these outputs:
0011
0110
0101
1100
1010
1001
The number of such combinations is computed as C(n,r)
in this example C(4,2)
which is 6.
Note that you can solve this just by increasing a number from 0 to 2^n and see if the count is OK. However, it is not a fast solution. I am considering solving the problem using bitset class in C++, and I need to increase N.
I want to add that there is an obvious recursive algorithm for this problem. Due to stack overflow, it is not a good answer. I have received a good answer here from Gosper's hack. While, I need to scale up the input and maybe use an MPI implementation for it later, I need a scalable library. Unsigned int is not big enough and I would rather a scalable and fast library like bitset. The solution is not applicable here while there is no addition in bitset library. any other solution?