Fixed getting nodes root ancestors

This commit is contained in:
Noah Santschi-Cooney 2020-08-07 00:58:34 +01:00
parent ae51b3b01c
commit d773220c67
No known key found for this signature in database
GPG key ID: 3B22282472C8AE48
4 changed files with 45 additions and 17 deletions

View file

@ -108,20 +108,18 @@ impl CachedStableGraph {
}
fn get_root_ancestors(&self, initial: NodeIndex, node: NodeIndex, visited: &mut HashSet<NodeIndex>) -> Vec<NodeIndex> {
if visited.contains(&node) {
return vec![node];
} else if node == initial && !visited.is_empty() {
if node == initial && !visited.is_empty() {
return vec![];
}
let parents = Rc::new(self.parent_node_indexes(node));
let parents = self.parent_node_indexes(node);
let mut collection = Vec::with_capacity(parents.len());
for ancestor in parents.as_ref() {
for ancestor in &parents {
visited.insert(*ancestor);
}
for ancestor in parents.as_ref() {
for ancestor in &parents {
let ancestors = self.parent_node_indexes(*ancestor);
if !ancestors.is_empty() {
collection.extend(self.get_root_ancestors(initial, *ancestor, visited));

View file

@ -202,18 +202,49 @@ fn test_graph_two_connected_nodes() {
#[test]
fn test_collect_root_ancestors() {
let mut graph = graph::CachedStableGraph::new();
{
let mut graph = graph::CachedStableGraph::new();
let idx0 = graph.add_node("0");
let idx1 = graph.add_node("1");
let idx2 = graph.add_node("2");
let idx0 = graph.add_node("0");
let idx1 = graph.add_node("1");
let idx2 = graph.add_node("2");
graph.add_edge(idx0, idx1, 2, 0, 0);
graph.add_edge(idx1, idx2, 3, 0, 0);
graph.add_edge(idx2, idx0, 5, 0, 0);
graph.add_edge(idx0, idx1, 2, 0, 0);
graph.add_edge(idx1, idx2, 3, 0, 0);
let roots = graph.collect_root_ancestors(idx0);
assert_eq!(roots, vec![idx2]);
let roots = graph.collect_root_ancestors(idx2);
assert_eq!(roots, vec![idx0]);
}
{
let mut graph = graph::CachedStableGraph::new();
let idx0 = graph.add_node("0");
let idx1 = graph.add_node("1");
let idx2 = graph.add_node("2");
let idx3 = graph.add_node("3");
graph.add_edge(idx0, idx1, 2, 0, 0);
graph.add_edge(idx0, idx2, 3, 0, 0);
graph.add_edge(idx1, idx3, 5, 0, 0);
let roots = graph.collect_root_ancestors(idx3);
assert_eq!(roots, vec![idx0]);
}
{
let mut graph = graph::CachedStableGraph::new();
let idx0 = graph.add_node("0");
let idx1 = graph.add_node("1");
let idx2 = graph.add_node("2");
let idx3 = graph.add_node("3");
graph.add_edge(idx0, idx1, 2, 0, 0);
graph.add_edge(idx2, idx3, 3, 0, 0);
graph.add_edge(idx1, idx3, 5, 0, 0);
let roots = graph.collect_root_ancestors(idx3);
assert_eq!(roots, vec![idx0, idx2]);
}
}
#[test]