Fix integer underflows in path and complete graph generators
This commit is contained in:
+10
-6
@@ -60,10 +60,11 @@ where
|
||||
///
|
||||
/// [Path graph]: https://en.wikipedia.org/wiki/Path_graph
|
||||
pub fn path<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Vertex>, Vec<G::Edge>) {
|
||||
let edge_capacity = n.saturating_sub(1);
|
||||
graph.reserve_vertices(n);
|
||||
graph.reserve_edges(n - 1);
|
||||
graph.reserve_edges(edge_capacity);
|
||||
let vertices: Vec<_> = (0..n).map(|_| graph.add_vertex()).collect();
|
||||
let edges = (0..n - 1)
|
||||
let edges = (0..edge_capacity)
|
||||
.map(|i| graph.add_edge(vertices[i], vertices[i + 1]))
|
||||
.collect();
|
||||
(vertices, edges)
|
||||
@@ -97,12 +98,15 @@ pub fn cycle<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Verte
|
||||
/// For `n == 0`, nothing is added. For `n == 1`, only a single vertex is added.
|
||||
///
|
||||
/// [Complete graph]: https://en.wikipedia.org/wiki/Complete_graph
|
||||
pub fn complete<G: GraphTopologyAddition>(graph: &mut G, n: usize) -> (Vec<G::Vertex>, Vec<G::Edge>) {
|
||||
let capacity = n * (n - 1) / 2;
|
||||
pub fn complete<G: GraphTopologyAddition>(
|
||||
graph: &mut G,
|
||||
n: usize,
|
||||
) -> (Vec<G::Vertex>, Vec<G::Edge>) {
|
||||
let edge_capacity = n * n.saturating_sub(1) / 2;
|
||||
graph.reserve_vertices(n);
|
||||
graph.reserve_edges(capacity);
|
||||
graph.reserve_edges(edge_capacity);
|
||||
let vertices: Vec<_> = (0..n).map(|_| graph.add_vertex()).collect();
|
||||
let mut edges = Vec::with_capacity(capacity);
|
||||
let mut edges = Vec::with_capacity(edge_capacity);
|
||||
for (i, &u) in vertices.iter().enumerate() {
|
||||
for &v in &vertices[i + 1..] {
|
||||
edges.push(graph.add_edge(u, v));
|
||||
|
||||
Reference in New Issue
Block a user