Created
September 8, 2022 08:44
-
-
Save trdthg/7b1d997500049a19746b654f536a53ea to your computer and use it in GitHub Desktop.
wheretoeat_v0.0.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rand::prelude::*; | |
struct Node { | |
name: String, | |
children: Vec<Node>, | |
} | |
impl Node { | |
pub fn new(name: &str) -> Self { | |
Self { | |
name: name.to_string(), | |
children: vec![], | |
} | |
} | |
pub fn add<F>(&mut self, name: &str, f: F) -> &mut Self | |
where | |
F: FnOnce(&mut Self) + Copy, | |
{ | |
let mut n = Node::new(name); | |
f(&mut n); | |
self.children.push(n); | |
self | |
} | |
pub fn add_node(mut self, node: Node) -> Self { | |
self.children.push(node); | |
self | |
} | |
pub fn execute<F>(&mut self, f: F) | |
where | |
F: FnOnce(&mut Self) + Copy, | |
{ | |
f(self); | |
} | |
} | |
fn random_select(node: &mut Node) { | |
println!("{}", node.name); | |
if node.children.is_empty() { | |
return; | |
} | |
let mut rng = thread_rng(); | |
let random_index = rng.gen_range(0..node.children.len()); | |
if let Some(child) = node.children.get_mut(random_index) { | |
child.execute(random_select); | |
}; | |
} | |
fn main() { | |
Node::new("Where to eat: ") | |
.add("东苑", |东苑| { | |
东苑.add("东 1", |东1| { | |
东1.add("一层", |一层| { | |
一层 | |
.add("1 窗", |_| {}) | |
.add("1 窗", |_| {}) | |
.add("1 窗", |_| {}); | |
}); | |
}); | |
}) | |
.add("西苑", |_| {}) | |
.execute(random_select); | |
Node::new("Where to eat: ") | |
.add_node( | |
Node::new("东苑") | |
.add_node(Node::new("东 1")) | |
.add_node(Node::new("东 2")) | |
.add_node(Node::new("东 3")), | |
) | |
.add_node(Node::new("西苑")) | |
.execute(random_select); | |
} | |
#[cfg(test)] | |
mod test { | |
use rand::{thread_rng, Rng}; | |
#[test] | |
fn test() { | |
let mut rng = thread_rng(); | |
let y = rng.gen_range(0..0); | |
println!("{}", y); | |
} | |
} |
Author
trdthg
commented
Sep 9, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment