All possible binary matrices with some properties

820 Views Asked by At

I need to generate all possible $4 \times 4$ symmetric binary matrices with $0$s on its main diagonal and in which $1$ appears $6$ times. Examples:

[[0,0,0,0],
 [0,0,1,1],
 [0,1,0,1],
 [0,1,1,0]] 

[[0,1,1,0],
 [1,0,1,0],
 [1,1,0,0],
 [0,0,0,0]]  

[[0,1,0,1],
 [1,0,0,1],
 [0,0,0,0],
 [1,1,0,0]]

How could I do that in Python?

1

There are 1 best solutions below

6
On

Here's a script that does it:

import numpy as np
from itertools import combinations

triangle = [(i,j) for i in range(4) for j in range (i+1,4)]

def matrices():
    for t in combinations(triangle,3):
        m = np.zeros((4,4))
        for c in t:
            m[c]=1
        yield m+m.transpose()

M = [m for m in matrices()]
print(M[-1]) # print the last matrix in the list
print(M[0])  # print the first matrix in the list
print(M[-1][-1,:]) #print the last row of the last matrix     
for m in matrices():
    print(m)