The following function returns a randomly generated adjacency matrix of size nxn, representing a graph.
import random
def random_adjacency_matrix(n):
matrix = [[random.randint(0, 1) for i in range(n)] for j in range(n)]
# No vertex connects to itself
for i in range(n):
matrix[i][i] = 0
# If i is connected to j, j is connected to i
for i in range(n):
for j in range(n):
matrix[j][i] = matrix[i][j]
return matrix
It is a very naive solution, and I'd like it to satisfy two additional requirements.
The graph the matrix represents must be fully connected, in other words there must not be any nodes that can't be reached from any other node in some number of steps.
Each node has a number of edges. Right now it's totally random, and thus fairly uniform how many edges a node has, and when
nis large the average number of edges tends to be large too for all graphs. I would like the average number of edges per node to vary more, independent of the size of the graph, so that some graphs have very few connections and others have a lot.
Edit: Using the networkx package, this seems to be what I want, only with point 1 above also satisfied:
import networkx, random
G = networkx.binomial_graph(50, random.random()) # 50 nodes, random probability of an edge
