0

For a given positive integer $N$, is there an efficient algorithm to generate all $N$-bit numbers in such an order that the number of 1s in the binary representation increases monotonically?

1 Answers1

2

To generate all $n$-bit numbers with $k$ ones, start out with the $k$ ones at the left, and in each step, move the right-most one that's followed by a zero to the right and move all ones following it right behind it; e.g.:

$$ 11100,11010,11001,10110,10101,10011,01110,01101,01011,00111\;. $$

You can keep a pointer to the $1$ that you're currently moving to the right, which also tells you how many ones to move to the left when this one can no longer move. For $k\gt n/2$, it will be more efficient to move the zeros instead of the ones.

joriki
  • 238,052