Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate all possible combinations of 0-1 matrix in Python?

How can generate all possible combinations of a 0-1 matrix of size K by N?

For example, if I take K=2 and N=2, I get the following combinations.

combination 1
[0, 0;
 0, 0]; 
combination 2
[1, 0;
 0, 0]; 
combination 3
[0, 1;
 0, 0]; 
combination 4
[0, 0;
 1, 0]; 
combination 5
[0, 0;
 0, 1]; 
combination 6
[1, 1;
 0, 0]; 
combination 7
[1, 0;
 1, 0]; 
combination 8
[1, 0;
 0, 1]; 
combination 9
[0, 1;
 1, 0]; 
combination 10
[0, 1;
 0, 1]; 
combination 11
[0, 0;
 1, 1]; 
combination 12
[1, 1;
 1, 0]; 
combination 13
[0, 1;
 1, 1]; 
combination 14
[1, 0;
 1, 1]; 
combination 15
[1, 1;
 0, 1]; 
combination 16
[1, 1;
 1, 1]; 
like image 281
drzbir Avatar asked Dec 25 '22 00:12

drzbir


1 Answers

A one-liner solution with numpy and itertools:

[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)]

Explanation: the product function returns a Cartesian product of its input. For instance, product([0, 1], [0, 1]) returns an iterator that comprises all possible permutations of [0, 1] and [0, 1]. In other words, drawing from a product iterator:

for i, j in product([0, 1], [0, 1]):

is actually equivalent to running two nested for-loops:

for i in [0, 1]:
    for j in [0, 1]:

The for-loops above already solve the problem at hand for a specific case of K, N = (1, 0). Continuing the above line of thought, to generate all possible zero/one states of a vector i, we need to draw samples from an iterator that is equivalent to a nested for-loop of depth l, where l = len(i). Luckily, itertools provides the framework to do just that with its repeat keyword argument. In the case of OP's problem this permutation depth should be K*N, so that it can be reshaped into a numpy array of proper sizes during each step of the list comprehension.

like image 179
Vlas Sokolov Avatar answered Dec 26 '22 14:12

Vlas Sokolov