The first algorithm creates a random undirected graph of
We define the graph as
We just need an algorithm that iterates through all the possible edges and randomly selects some of them, until exactly
The following is the pseudo code of the algorithm given as an answer.
We define a function that takes
First the
and that explains line 2 in the pseudo code.
Then a double for loop starts which produces virtually all the edges in pairs of vertices
To decide whether or not to include a node in the graph, do the following procedure:
first call the rand function to generate a random value from
The probability that
Then
Once k becomes 0, the algorithm stops (returns E immediately). There is a case,that at some point N becomes equal to k. When this equality is valid, in the if statement of line 7, we will essentially have
In practice this means that if the remaining edges are equal in number to the edges that must be contained in E, then all must be chosen necessarily.
This ensures that the algorithm always provides a valid solution.
The above algorithm is located in the file src/randgraph.py. The createRandomGraph function contains the actual algorithm. Notice that
At the end of the file there is block comment with an example. Feel free to uncomment it and test it yourself. Here is an example output:
$ python3 randgraph.py
Time elapsed 1.2120999599574134e-05
[(1, 4), (2, 3), (2, 4), (3, 4)]
$