Add backtrack function.
This commit is contained in:
parent
b078e13cb6
commit
f5b0a710e0
27
src/lib.rs
27
src/lib.rs
|
|
@ -12,6 +12,7 @@
|
|||
extern crate alloc;
|
||||
mod node;
|
||||
|
||||
use alloc::collections::vec_deque::VecDeque;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::vec;
|
||||
use alloc::vec::Vec;
|
||||
|
|
@ -58,7 +59,7 @@ impl<NodeValueT: NodeValue> Graph<NodeValueT> {
|
|||
node.set_value(value);
|
||||
return Ok(());
|
||||
}
|
||||
return Err(GraphError::from_msg("Can't set value of invalid key."));
|
||||
Err(GraphError::from_msg("Can't set value of invalid key."))
|
||||
}
|
||||
|
||||
/// Get the value of key `key` if the key is valid.
|
||||
|
|
@ -104,7 +105,7 @@ impl<NodeValueT: NodeValue> Graph<NodeValueT> {
|
|||
}
|
||||
}
|
||||
|
||||
return Ok(leaf_keys);
|
||||
Ok(leaf_keys)
|
||||
}
|
||||
|
||||
/// Return all keys ordered like you were doing
|
||||
|
|
@ -126,6 +127,22 @@ impl<NodeValueT: NodeValue> Graph<NodeValueT> {
|
|||
|
||||
Ok(visited_keys)
|
||||
}
|
||||
|
||||
/// Given a key, return the vec of keys connecting that key to the root.
|
||||
/// Order is root->key inclusive.
|
||||
pub fn backtrack_from_key(&self, key: &Key) -> Result<Vec<Key>, GraphError> {
|
||||
let mut curr_key = key.clone();
|
||||
let mut deque = VecDeque::<Key>::new();
|
||||
deque.push_front(curr_key.clone());
|
||||
|
||||
while curr_key != self.root_key() {
|
||||
let new_parent = self.parent_of(&curr_key)?.unwrap();
|
||||
deque.push_front(new_parent.clone());
|
||||
curr_key = new_parent;
|
||||
}
|
||||
|
||||
Ok(Vec::from(deque))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
|
@ -193,6 +210,7 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn graph_search() {
|
||||
// Build the graph.
|
||||
let root_val = NodeType::new(1.0);
|
||||
let mut graph = Graph::new(root_val);
|
||||
|
||||
|
|
@ -212,11 +230,16 @@ mod tests {
|
|||
let fifth_add_res = graph.add(fifth_val, 2);
|
||||
assert!(fifth_add_res.is_ok());
|
||||
|
||||
// Do the testing.
|
||||
let leaf_keys = graph.find_leaf_keys().unwrap();
|
||||
assert!(leaf_keys.len() == 2);
|
||||
|
||||
let keys_by_depth = graph.get_keys_by_depth().unwrap();
|
||||
let expected_keys_by_depth = vec![0, 2, 4, 1, 3];
|
||||
assert!(keys_by_depth == expected_keys_by_depth);
|
||||
|
||||
let backtracked_keys = graph.backtrack_from_key(&4).unwrap();
|
||||
let expected_backtracked_keys = vec![0, 2, 4];
|
||||
assert!(backtracked_keys == expected_backtracked_keys);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue