Skip to content

Instantly share code, notes, and snippets.

@jcchurch
Last active April 18, 2018 15:53
Show Gist options
  • Save jcchurch/c1f4b3092b59d4db3b06f50feb98a423 to your computer and use it in GitHub Desktop.
Save jcchurch/c1f4b3092b59d4db3b06f50feb98a423 to your computer and use it in GitHub Desktop.
Generates the edge list for a randomly generated graph. The first value presented is the number of verticies in the graph. The second is the number of edges. Every triplet of values after that represents an edge consisting of a source vertex, a destination vertex, and the weight of that edge.
#!/usr/bin/env python3
"""
Generates the edge list for a randomly generated graph.
- The first value presented is the number of verticies in the graph.
- The second is the number of edges.
- Every triplet of values after that represents an edge consisting of a source vertex,
a destination vertex, and the weight of that edge.
Notes.
- The number of verticies in the graph is required using the "-v" argument.
- The number of edges may be specified but can also be selected randomly.
- If random, the number of edges will be a randomly selected value from v to v*(v-1).
- The graph will not generate reflexive edges.
James Church
2018-04-18
"""
import argparse
import random
def generateGraph(v, e, m):
print(v)
print(e)
matrix = [0] * (v*v)
for i in range(e):
a = random.randint(0, v-1)
b = random.randint(0, v-1)
while a == b:
b = random.randint(0, v-1)
while matrix[a * v + b] == 1:
a = random.randint(0, v-1)
b = random.randint(0, v-1)
while a == b:
b = random.randint(0, v-1)
matrix[a * v + b] = 1
d = random.randint(1, m)
print(a, b, d)
p = argparse.ArgumentParser(description="Generates the edge list for a randomly generated graph.")
p.add_argument("-v", "--vertices", metavar="15", dest="v", help="Number of verticies.")
p.add_argument("-e", "--edges", metavar="50", dest="e", help="Number of edges.")
p.add_argument("-m", "--maxweight", metavar="15", dest="m", default="1", help="Max weight of edge (default is 1)")
options = p.parse_args()
if options.v is not None:
v = int(options.v);
e = random.randint(v, v*(v-1))
if options.e is not None:
e = int(options.e)
if e < 0:
e = 0
if e > v*(v-1):
e = v*(v-1)
m = int(options.m)
if m < 1:
m = 1
generateGraph(v, e, m)
else:
print("For help, use the -h flag.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment