Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate all possible combinations n-bit strings?

Given a positive integer n, I want to generate all possible n bit combinations in matlab.
For ex : If n=3, then answer should be

000
001
010
011
100
101
110
111

How do I do it ? I want to actually store them in matrix. I tried

for n=1:2^4 
r(n)=dec2bin(n,5); 
end; 

but that gave error "In an assignment A(:) = B, the number of elements in A and B must be the same.

like image 928
Happy Mittal Avatar asked Mar 19 '12 08:03

Happy Mittal


People also ask

What are n bit strings?

They are strings consisting either 0 or 1 as each letter. They can also be seen as binary numbers in mathematics. They can also have variable length.

How many binary numbers of length N are possible?

Approach: For any digit length N, there will be 2N binary numbers.

How do you create a binary string?

' wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by '0' or '1'. We pass index of next character to the recursive function. If the current character is a wildcard character '? ', we replace it with '0' or '1' and do the same for all remaining characters.

How many binary strings does length 4 have?

Answer and Explanation: A bit string of length 4 would have all the binary numbers between, 0000 and 1111 . There can be no other permutations or arrangements of the digits that can contain consecutive 1s. Hence there must be 10 bit-strings of length 4 which do not have consecutive 1s.


2 Answers

Just loop over all integers in [0,2^n), and print the number as binary. If you always want to have n digits (e.g. insert leading zeros), this would look like:

for ii=0:2^n-1,
    fprintf('%0*s\n', n, dec2bin(ii));
end

Edit: there are a number of ways to put the results in a matrix. The easiest is to use

x = dec2bin(0:2^n-1);

which will produce an n-by-2^n matrix of type char. Each row is one of the bit strings.

If you really want to store strings in each row, you can do this:

x = cell(1, 2^n);
for ii=0:2^n-1,
    x{ii} = dec2bin(ii);
end

However, if you're looking for efficient processing, you should remember that integers are already stored in memory in binary! So, the vector:

x = 0 : 2^n-1;

Contains the binary patterns in the most memory efficient and CPU efficient way possible. The only trade-off is that you will not be able to represent patterns with more than 32 of 64 bits using this compact representation.

like image 92
André Caron Avatar answered Sep 20 '22 14:09

André Caron


This is a one-line answer to the question which gives you a double array of all 2^n bit combinations:

bitCombs = dec2bin(0:2^n-1) - '0'

like image 37
theOne Avatar answered Sep 24 '22 14:09

theOne