diff --git a/06_breadth-first_search/rust/Cargo.lock b/06_breadth-first_search/rust/Cargo.lock new file mode 100644 index 0000000..3c57ea9 --- /dev/null +++ b/06_breadth-first_search/rust/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "breadth_first" +version = "0.1.0" diff --git a/06_breadth-first_search/rust/Cargo.toml b/06_breadth-first_search/rust/Cargo.toml new file mode 100644 index 0000000..7fa294f --- /dev/null +++ b/06_breadth-first_search/rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "breadth_first" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/06_breadth-first_search/rust/src/main.rs b/06_breadth-first_search/rust/src/main.rs new file mode 100644 index 0000000..936cb6b --- /dev/null +++ b/06_breadth-first_search/rust/src/main.rs @@ -0,0 +1,68 @@ +use std::collections::{HashMap, VecDeque}; +use std::fmt; + +#[derive(Eq, Hash, PartialEq)] +struct Person(String); + +impl Person { + fn is_seller(&self) -> bool { + self.0.ends_with('m') + } +} + +impl fmt::Display for Person { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&self.0) + } +} + +fn search(graph: &HashMap<&Person, Vec<&Person>>, start: &Person) { + let mut search_queue = VecDeque::new(); + search_queue.push_back(start); + + let mut searched: Vec<&Person> = Vec::with_capacity(graph.len()); + loop { + match search_queue.pop_front() { + Some(person) => { + if !searched.contains(&person) { + if person.is_seller() { + println!("{} is a mango seller!", person); + break; + } else { + for p in graph.get(&person).unwrap() { + search_queue.push_back(p); + searched.push(person); + } + } + } + } + None => { + println!("no mango seller found!"); + break; + } + } + } +} + +fn main() { + let you = Person("you".to_string()); + let alice = Person("alice".to_string()); + let bob = Person("bob".to_string()); + let claire = Person("claire".to_string()); + let anuj = Person("anuj".to_string()); + let peggy = Person("peggy".to_string()); + let thom = Person("thom".to_string()); + let jonny = Person("jonny".to_string()); + + let mut graph = HashMap::new(); + graph.insert(&you, vec![&alice, &bob, &claire]); + graph.insert(&bob, vec![&anuj, &peggy]); + graph.insert(&alice, vec![&peggy]); + graph.insert(&claire, vec![&thom, &jonny]); + graph.insert(&anuj, vec![]); + graph.insert(&peggy, vec![]); + graph.insert(&thom, vec![]); + graph.insert(&jonny, vec![]); + + search(&graph, &you); +}