add rust breadth first search (#293)
This commit is contained in:
7
06_breadth-first_search/rust/Cargo.lock
generated
Normal file
7
06_breadth-first_search/rust/Cargo.lock
generated
Normal file
@@ -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"
|
||||
6
06_breadth-first_search/rust/Cargo.toml
Normal file
6
06_breadth-first_search/rust/Cargo.toml
Normal file
@@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "breadth_first"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
68
06_breadth-first_search/rust/src/main.rs
Normal file
68
06_breadth-first_search/rust/src/main.rs
Normal file
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user