Skip to content

Commit

Permalink
implement helper to visualize the graph
Browse files Browse the repository at this point in the history
  • Loading branch information
kcaffrey committed Dec 23, 2023
1 parent 14d14df commit 596d63e
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/bin/23.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::collections::BinaryHeap;
use std::{
collections::BinaryHeap,
fmt::{Display, Write},
};

use tinyvec::ArrayVec;

Expand Down Expand Up @@ -209,6 +212,36 @@ impl Direction {
const ALL: [Self; 4] = [Self::Up, Self::Down, Self::Left, Self::Right];
}

impl Display for Graph {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn format_vertex(vertex: usize) -> String {
let mut ret = String::new();
if vertex > 25 {
ret.push(char::from((vertex / 26) as u8 + b'A'));
}
ret.push(char::from((vertex % 26) as u8 + b'A'));
ret
}
for vertex in 0..self.vertices {
if !self.adjacency[vertex].is_empty() {
writeln!(
f,
"{} -> {{{}}}",
format_vertex(vertex),
self.adjacency[vertex]
.iter()
.fold(String::new(), |mut s, &(n, _)| {
write!(&mut s, "{} ", format_vertex(n)).expect("should succeed");
s
})
.trim_end()
)?;
}
}
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 596d63e

Please sign in to comment.