Correct display

This commit is contained in:
rendo 2026-04-01 10:06:17 +05:00
commit f1633ee8d5

View file

@ -22,7 +22,10 @@ impl Genome {
return Err(PlantCreationError::EmptyEdges); return Err(PlantCreationError::EmptyEdges);
} }
let mut graph: Vec<(Gene,Vec<usize>)>= nodes.iter().map(|gene|{(gene.clone(),Vec::new())}).collect(); let mut graph: Vec<(Gene,Vec<usize>)> = Vec::new();
for gene in nodes {
graph.push((gene,Vec::new()));
}
for edge in edges { for edge in edges {
graph[edge.0].1.push(edge.1); graph[edge.0].1.push(edge.1);
} }
@ -36,13 +39,15 @@ impl Genome {
impl Display for Genome { impl Display for Genome {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let indents = { let indents = {
let mut result: Vec<(usize,Gene)> = vec![(0,self.graph[0].0.clone())]; let mut result: Vec<(usize, Gene)> = Vec::new();
let mut tree: VecDeque<(usize,&Vec<usize>)> = VecDeque::from([(0,&self.graph[0].1)]); let mut stack: Vec<(usize, usize)> = vec![(0, 0)]; // (node_index, depth)
while tree.is_empty() == false {
let (depth,children) = tree.pop_front().unwrap(); while let Some((node, depth)) = stack.pop() {
for child in children { result.push((depth, self.graph[node].0.clone()));
result.push((depth+1,self.graph[*child].0.clone()));
tree.push_back((depth+1,&self.graph[*child].1)); // push in reverse so left-most child is processed first
for &child in self.graph[node].1.iter().rev() {
stack.push((child, depth + 1));
} }
} }