/// <summary> /// Returns a random simple graph containing <tt>V</tt> vertices and <tt>E</tt> edges. /// </summary> /// <param name="v">V the number of vertices</param> /// <param name="e">E the number of edges</param> /// <returns> random simple graph on <tt>V</tt> vertices, containing a total of <tt>E</tt> edges</returns> /// <exception cref="ArgumentException">if no such simple graph exists</exception> public static Graph Simple(int v, int e) { if (e > (long)v * (v - 1) / 2) { throw new ArgumentException("Too many edges"); } if (e < 0) { throw new ArgumentException("Too few edges"); } var g = new Graph(v); var set = new SET <EdgeU>(); while (g.E < e) { var ve = StdRandom.Uniform(v); var we = StdRandom.Uniform(v); var edge = new EdgeU(ve, we); if ((ve == we) || set.Contains(edge)) { continue; } set.Add(edge); g.AddEdge(ve, we); } return(g); }
/// <summary> /// Returns a random simple bipartite graph on <tt>V1</tt> and <tt>V2</tt> vertices /// with <tt>E</tt> edges. /// </summary> /// <param name="v1">V1 the number of vertices in one partition</param> /// <param name="v2">V2 the number of vertices in the other partition</param> /// <param name="e">E the number of edges</param> /// <returns>a random simple bipartite graph on <tt>V1</tt> and <tt>V2</tt> vertices, containing a total of <tt>E</tt> edges</returns> /// <exception cref="ArgumentException">if no such simple bipartite graph exists</exception> public static Graph Bipartite(int v1, int v2, int e) { if (e > (long)v1 * v2) { throw new ArgumentException("Too many edges"); } if (e < 0) { throw new ArgumentException("Too few edges"); } var g = new Graph(v1 + v2); var vertices = new int[v1 + v2]; for (var i = 0; i < v1 + v2; i++) { vertices[i] = i; } StdRandom.Shuffle(vertices); var set = new SET <EdgeU>(); while (g.E < e) { var i = StdRandom.Uniform(v1); var j = v1 + StdRandom.Uniform(v2); var edge = new EdgeU(vertices[i], vertices[j]); if (set.Contains(edge)) { continue; } set.Add(edge); g.AddEdge(vertices[i], vertices[j]); } return(g); }