How do I generate all possible combinations of n-bit strings? I need to generate all combinations of 20-bit strings in a fastest way possible. (my current implementation is done with bitwise AND and right shift operation, but I am looking for a faster technique).
I need to store the bit-strings in an array (or list) for the corresponding decimal numbers, like --
0 --> 0 0 0
1 --> 0 0 1
2 --> 0 1 0
... etc.
any idea?
Just output numbers from 0 to 2^n - 1 in binary representation with exactly n digits.
This solution is in Python. (versions 2.7 and 3.x should work)
It finds the width of the maximum number and then pairs the int with the int formatted in binary with every formatted string being right padded with zero's to fill the maximum width if necessary. (The pprint stuff is just to get a neat printout for this forum and could be left out).
An
unsigned long
is a sequence of bits.If what you want is a string of characters
'0'
and'1'
, then you could converti
to that format each time. You might be able to get a speed-up taking advantage of the fact that consecutive numbers normally share a long initial substring. So you could do something like this:I've only increased from 1 loop to 2 there, but I do a little over 50% as much converting from bits to chars as before. You could experiment with the following:
'0'
, change it to a'1'
, and change all the'1'
s after it to'0'
.To fiendishly optimize
write_bitstring
, multiples of 4 are good because on most architectures you can blit 4 characters at a time in a word write:To start:
Function definition:
I haven't tested any of this: obviously you're responsible for writing a benchmark that you can use to experiment.
conversion of the int version i to binary string left as an exercise to the OP.
Python