Day 6 part 1 reimplemented with a directed graph

Using petgraph crate.
This commit is contained in:
Tyler Hallada 2019-12-08 03:17:02 -05:00
parent c71ca99eaa
commit 3e9121539b
3 changed files with 96 additions and 34 deletions

26
day6/Cargo.lock generated
View File

@ -3,4 +3,30 @@
[[package]] [[package]]
name = "day6" name = "day6"
version = "0.1.0" version = "0.1.0"
dependencies = [
"petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "fixedbitset"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "ordermap"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "petgraph"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
"ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
]
[metadata]
"checksum fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33"
"checksum ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a86ed3f5f244b372d6b1a00b72ef7f8876d0bc6a78a4c9985c53614041512063"
"checksum petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f"

View File

@ -7,3 +7,4 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
petgraph = "0.4.13"

View File

@ -4,14 +4,23 @@ use std::fs::File;
use std::io::{prelude::*, BufReader}; use std::io::{prelude::*, BufReader};
use std::result; use std::result;
use petgraph::graph::NodeIndex;
use petgraph::{Direction, Graph};
const INPUT: &str = "input/input.txt"; const INPUT: &str = "input/input.txt";
type Result<T> = result::Result<T, Box<dyn Error>>; type Result<T> = result::Result<T, Box<dyn Error>>;
fn read_orbit_map(filename: &str) -> Result<HashMap<String, Option<String>>> { struct OrbitMap {
graph: Graph<String, ()>,
map: HashMap<String, NodeIndex>,
}
fn read_orbit_map(filename: &str) -> Result<OrbitMap> {
let file = File::open(filename)?; let file = File::open(filename)?;
let reader = BufReader::new(file); let reader = BufReader::new(file);
let mut objects: HashMap<String, Option<String>> = HashMap::new(); let mut graph = Graph::<String, ()>::new();
let mut map: HashMap<String, NodeIndex> = HashMap::new();
for line in reader.lines() { for line in reader.lines() {
let line = line?; let line = line?;
@ -25,28 +34,44 @@ fn read_orbit_map(filename: &str) -> Result<HashMap<String, Option<String>>> {
.expect("Invalid line, no orbiter part.") .expect("Invalid line, no orbiter part.")
.to_string(); .to_string();
objects.entry(mass_name.clone()).or_insert(None); let mass_index = match map.get(&mass_name) {
objects.insert(orbiter_name.clone(), Some(mass_name)); None => {
let index = graph.add_node(mass_name.clone());
map.insert(mass_name, index);
index
}
Some(index) => *index,
};
let orbiter_index = match map.get(&orbiter_name) {
None => {
let index = graph.add_node(orbiter_name.clone());
map.insert(orbiter_name, index);
index
}
Some(index) => *index,
};
graph.update_edge(orbiter_index, mass_index, ());
} }
Ok(objects) Ok(OrbitMap { graph, map })
} }
fn get_orbit_count(orbit_map: &HashMap<String, Option<String>>, orbiter: String) -> u32 { fn get_orbit_count(orbit_map: &OrbitMap, orbiter: NodeIndex) -> u32 {
match orbit_map.get(&orbiter) { for neighbor in orbit_map
None => panic!("Incomplete orbit map"), .graph
Some(mass) => match mass { .neighbors_directed(orbiter, Direction::Outgoing)
None => return 0, {
Some(mass) => return 1 + get_orbit_count(orbit_map, mass.to_string()), return 1 + get_orbit_count(orbit_map, neighbor);
},
} }
return 0;
} }
fn get_orbit_count_checksum(orbit_map: &HashMap<String, Option<String>>) -> u32 { fn get_orbit_count_checksum(orbit_map: &OrbitMap) -> u32 {
let mut checksum = 0; let mut checksum = 0;
for orbiter in orbit_map.keys() { for orbiter in orbit_map.map.keys() {
checksum += get_orbit_count(&orbit_map, orbiter.to_string()); let node = orbit_map.map.get(orbiter).expect("Incomplete orbit map");
checksum += get_orbit_count(&orbit_map, *node);
} }
checksum checksum
@ -58,6 +83,11 @@ fn solve_part1() -> Result<u32> {
} }
fn solve_part2() -> Result<i32> { fn solve_part2() -> Result<i32> {
let orbit_map = read_orbit_map(INPUT)?;
let you = orbit_map.map.get("YOU").expect("YOU not found in orbit map");
let san = orbit_map.map.get("SAN").expect("SAN not found in orbit map");
// let mut bfs = Bfs::new(&orbit_map.graph, *you);
// that BFS doesn't tell me the edges from node for each iteration. guess I'll roll my own
Ok(0) Ok(0)
} }
@ -76,26 +106,31 @@ mod tests {
#[test] #[test]
fn reads_orbit_map() { fn reads_orbit_map() {
let orbit_map = read_orbit_map(TEST_INPUT).unwrap();
assert_eq!( assert_eq!(
read_orbit_map(TEST_INPUT).unwrap(), format!("{:?}", orbit_map.graph),
[ "Graph { \
("COM".to_string(), None), Ty: \"Directed\", \
("B".to_string(), Some("COM".to_string())), node_count: 12, \
("C".to_string(), Some("B".to_string())), edge_count: 11, \
("D".to_string(), Some("C".to_string())), edges: (1, 0), (2, 1), (3, 2), (4, 3), (5, 4), (6, 1), (7, 6), \
("E".to_string(), Some("D".to_string())), (8, 3), (9, 4), (10, 9), (11, 10), \
("F".to_string(), Some("E".to_string())), node weights: {\
("G".to_string(), Some("B".to_string())), 0: \"COM\", \
("H".to_string(), Some("G".to_string())), 1: \"B\", \
("I".to_string(), Some("D".to_string())), 2: \"C\", \
("J".to_string(), Some("E".to_string())), 3: \"D\", \
("K".to_string(), Some("J".to_string())), 4: \"E\", \
("L".to_string(), Some("K".to_string())), 5: \"F\", \
] 6: \"G\", \
.iter() 7: \"H\", \
.cloned() 8: \"I\", \
.collect() 9: \"J\", \
); 10: \"K\", \
11: \"L\"\
} \
}",
)
} }
#[test] #[test]