I wrote a function that returns a directed graph as an adjacency matrix. The function requires two arguments: the amount of nodes and the amount of edges. At first, nodes are placed and instantly connected to the graph. When all nodes are added, random edges are created until all edges are placed.
Code:
public int(,) GenerateMatrix(int Nodes, int Edges)
{
if (Edges < Nodes - 1) throw new Exception("Too few edges");
if (Edges > Nodes * (Nodes - 1)) throw new Exception("Too many edges");
int(,) adjacencyMatrix = new int(Nodes, Nodes);
// Gives every cell a value of zero
for (int y = 0; y < Nodes; y++)
{
for (int x = 0; x < Nodes; x++)
{
adjacencyMatrix(x, y) = 0;
}
}
int placedEdges = 0;
for (int i = 1; i < Nodes; i++)
{
// produce edge between rnd(0, amountofnodes) to new node
int fromVertex = random.Next(0, i);
int weight = random.Next(1, 10);
adjacencyMatrix(i, fromVertex) = weight;
placedEdges++;
}
while (placedEdges < Edges)
{
int fromVertex = random.Next(0, Nodes);
int weight = random.Next(1, 10);
int targetVertex = random.Next(0, Nodes);
while (targetVertex == fromVertex || adjacencyMatrix(targetVertex, fromVertex) != 0) //|| adjacencyMatrix(fromVertex, targetVertex) != 0)// tredje condition tar bort parallella kanter
{
fromVertex = random.Next(0, Nodes);
targetVertex = random.Next(0, Nodes);
}
adjacencyMatrix(targetVertex, fromVertex) = weight;
placedEdges++;
}
return adjacencyMatrix;
}