From fcc0b8d9073bcd75c2ee5983b3fe4cf1c3a4256e Mon Sep 17 00:00:00 2001 From: Youngjoon Lee <5462944+youngjoon-lee@users.noreply.github.com> Date: Wed, 18 Dec 2024 12:04:24 +0900 Subject: [PATCH] add function to calculate longest path len --- .../blendnet-sims/src/node/blend/topology.rs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/simlib/blendnet-sims/src/node/blend/topology.rs b/simlib/blendnet-sims/src/node/blend/topology.rs index f01e890..30223f1 100644 --- a/simlib/blendnet-sims/src/node/blend/topology.rs +++ b/simlib/blendnet-sims/src/node/blend/topology.rs @@ -83,9 +83,44 @@ fn check_equal_conns(topology: &Topology, peering_degree: usize) -> bool { .all(|(_, peers)| peers.len() == peering_degree) } +/// Returns the longest path length in the topology. +fn longest_path_len(topology: &Topology) -> usize { + let mut max_len = 0; + topology.keys().for_each(|&node| { + let len = longest_path_len_from(topology, node); + max_len = std::cmp::max(max_len, len); + }); + max_len +} + +/// Returns the longest path length from the start node in the topology. +fn longest_path_len_from(topology: &Topology, start_node: NodeId) -> usize { + let mut visited: HashSet = HashSet::from_iter(std::iter::once(start_node)); + let mut step: HashSet = topology.get(&start_node).unwrap().iter().copied().collect(); + + let mut step_count = 0; + while visited.len() < topology.len() { + let mut next_step = HashSet::new(); + for &node in step.iter() { + if visited.insert(node) { + for peer in topology.get(&node).unwrap().iter() { + if !visited.contains(peer) { + next_step.insert(*peer); + } + } + } + } + step = next_step; + step_count += 1; + } + step_count +} + #[cfg(test)] mod tests { use netrunner::node::NodeIdExt; + use rand::SeedableRng; + use rand_chacha::ChaCha8Rng; use super::*; @@ -124,4 +159,13 @@ mod tests { } } } + + #[test] + fn test_longest_path_len() { + let nodes = (0..100).map(NodeId::from_index).collect::>(); + let peering_degree = 4; + let mut rng = ChaCha8Rng::seed_from_u64(0); + let topology = build_topology(&nodes, peering_degree, &mut rng); + assert!(longest_path_len(&topology) > 0); + } }