Extract out function to build orbit tree

This commit is contained in:
Wesley Moore 2019-12-07 16:16:00 +11:00
parent 93d609a25e
commit 69c072e211
No known key found for this signature in database
GPG key ID: BF67766C0BC2D0EE

View file

@ -29,6 +29,14 @@ fn parse_input(input: &str) -> Vec<Orbit<'_>> {
} }
fn number_of_orbits(input: &[Orbit<'_>]) -> usize { fn number_of_orbits(input: &[Orbit<'_>]) -> usize {
let nodes = build_tree(input);
// Now traverse the node and sum the orbits of each one
(0..nodes.len())
.map(|index| count_orbits(&nodes, index, 0))
.sum()
}
fn build_tree<'a>(input: &'a [Orbit<'a>]) -> Vec<Node<'a>> {
// Build the tree from the input // Build the tree from the input
let mut nodes: Vec<Node<'_>> = Vec::with_capacity(input.len()); let mut nodes: Vec<Node<'_>> = Vec::with_capacity(input.len());
@ -65,10 +73,7 @@ fn number_of_orbits(input: &[Orbit<'_>]) -> usize {
}); });
} }
// Now traverse the node and sum the orbits of each one nodes
(0..nodes.len())
.map(|index| count_orbits(&nodes, index, 0))
.sum()
} }
fn count_orbits(nodes: &[Node], node_index: usize, count: usize) -> usize { fn count_orbits(nodes: &[Node], node_index: usize, count: usize) -> usize {