1

I need to generate all possible 4x4 binary matrices that have zeros along the main diagonal, are symmetric, and have six entries equal to 1. Some 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?

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
MathNew C
  • 11
  • 3

1 Answers1

1

This amounts to choosing which three of the six entries above the diagonal are 1.

From the list of above-the-diagonal positions in a 4 by 4 matrix:

sage: positions = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

use Sage's Subsets to get all subsets of size 3 of those positions.

sage: S = Subsets([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)], 3)

Then build the corresponding matrices.

sage: [matrix(ZZ, 4, lambda i, j: (i, j) in s or (j, i) in s) for s in S]
[
[0 1 1 1]  [0 1 1 0]  [0 1 1 0]  [0 1 1 0]  [0 1 0 1]  [0 1 0 1]
[1 0 0 0]  [1 0 1 0]  [1 0 0 1]  [1 0 0 0]  [1 0 1 0]  [1 0 0 1]
[1 0 0 0]  [1 1 0 0]  [1 0 0 0]  [1 0 0 1]  [0 1 0 0]  [0 0 0 0]
[1 0 0 0], [0 0 0 0], [0 1 0 0], [0 0 1 0], [1 0 0 0], [1 1 0 0],

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

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

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

Note that these are the adjacency matrices for all graphs with three edges on four labeled vertices.

If you want un-labeled vertices, or equivalently the list of adjacency matrices of equivalence classes of graphs with three edges on four vertices, you could use Nauty to enumerate them. Here is how to do that from Sage:

sage: G = graphs.nauty_geng("4 3:3")
sage: G
<generator object nauty_geng at 0x21c89a0f0>
sage: [g.adjacency_matrix() for g in G]
[
[0 0 0 1]  [0 0 1 1]  [0 0 1 1]
[0 0 0 1]  [0 0 0 1]  [0 0 0 0]
[0 0 0 1]  [1 0 0 0]  [1 0 0 1]
[1 1 1 0], [1 1 0 0], [1 0 1 0]
]
Samuel Lelièvre
  • 3,212
  • 1
  • 14
  • 27