Problem
I need to create 32 bit numbers (signed or unsigned does not matter, the most significant bit will never be set in any case), and each number must have a given number of bits.
Naive decision
The simplest solution is, of course, to start from scratch. In the cycle, the number now increases by one, the number of bits is counted, if the counter has the desired value, the number is stored in the list if the cycle does not repeat. The loop is stopped if enough numbers are found. Of course, this works great, but it's terribly slow as soon as the number of desired bits gets very high.
The best decision
The simplest number having (say) 5 Bits, a given number in which the first 5 bits are set. This number can be easily created. Inside the loop, the first bit is set, and the number is shifted to the left by one. This loop runs 5 times, and I found the first number with 5 bits. The following pair of numbers is easy to create. Now we will pretend that the number should be 6 bits wide, and the top one is not set. Now we begin to shift the first zero bit to the right, so we get 101111, 110111, 111011, 111101, 111110. We could repeat this by adding another edge and repeat this process. 0111110, 1011110, 1101110, etc. However, in this way the numbers will grow much faster than necessary, because, using this simple approach, we leave numbers like 1010111.
So, is there a better way to create all possible permutations, a general approach that you can use, regardless of how many bits the next number will have and no matter how many sets of bits you need to set?
algorithm binary permutation combinations
Mecki Feb 03 '09 at 11:50 2009-02-03 11:50
source share