Suppose I wanted to enumerate all 4-bit patterns i.e. from 0 (0000) to 15 (1111)
. One way is the "truth table" approach:
0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, ... 1111
This approach is the equivalent of counting up from 0 to 15 in decimal.
Another approach would be using Gray codes, in which only one bit is flipped at a time:
0000, 0001, 0011, 0010, 0110, ... 1000
How would I systematically enumerate all numbers in an order that minimizes the sum of the bits? For example, something along the lines of:
0000, 0001, 0010, 0100, 1000, 0011, 0101, 1001, 0110, 1010, 1001, 0111, 1011, 1101, 1110, 1111
for the 4-bit example.
Ultimately, it would be nice to extend this to any base, but the binary case seems the most straightforward to implement.
EDIT: I probably should have made it clear that the method must be generative i.e. I can't compute all the possible sequences and then sort them; the solution must iteratively produce the sequence in an order similar to the one specified.