summaryrefslogtreecommitdiff
path: root/rust/theBook/chapter-8-common-collections/practice/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/theBook/chapter-8-common-collections/practice/src/main.rs')
-rw-r--r--rust/theBook/chapter-8-common-collections/practice/src/main.rs87
1 files changed, 87 insertions, 0 deletions
diff --git a/rust/theBook/chapter-8-common-collections/practice/src/main.rs b/rust/theBook/chapter-8-common-collections/practice/src/main.rs
new file mode 100644
index 0000000..ba63d64
--- /dev/null
+++ b/rust/theBook/chapter-8-common-collections/practice/src/main.rs
@@ -0,0 +1,87 @@
+use std::{{collections::HashMap as hm, io}};
+use rand::Rng;
+
+fn main() {
+ median();
+ pig_latin(&"appearance is the best".to_string());
+
+ add_emp();
+}
+
+fn median() {
+ // generate a list of number
+ let mut arr = Vec::new();
+ for _x in 0..100 {
+ let p = rand::thread_rng().gen_range(1..=10);
+ arr.push(p);
+ }
+
+ // count each number's appearance
+ let mut num_hash = hm::new();
+ for x in &arr {
+ let count = num_hash.entry(x).or_insert(0);
+ *count += 1;
+ }
+
+ // get most appearance
+ let mut key = 0;
+ let mut ret = 0;
+ for (k,v) in num_hash.iter() {
+ if *v > ret {
+ key = **k;
+ ret = *v;
+ }
+ }
+
+ println!("most appearance: {key} {ret}");
+}
+
+fn pig_latin(st: &String) {
+ let vowel = ['a', 'e', 'i', 'o', 'u'];
+ for w in st.split_whitespace() {
+ for v in vowel {
+ if w.starts_with(v) {
+ println!("{:?}",format!("{w}-hay"));
+ break;
+ } else {
+ let pl = w.chars().nth(0).unwrap();
+ println!("{:?}",format!("{w}-{pl}ay"));
+ break;
+ }
+ }
+ }
+}
+
+fn add_emp() {
+ println!("Employee interface");
+
+ let mut hash: hm<String, Vec<String>> = hm::new();
+
+ loop {
+ let mut rd = String::new();
+ println!("enter name: ");
+ io::stdin()
+ .read_line(&mut rd)
+ .expect("failed to read line");
+
+ if rd.trim() == "q" {
+ break;
+ }
+
+ let mut wd = String::new();
+ println!("enter department: ");
+ io::stdin()
+ .read_line(&mut wd)
+ .expect("failed to read line");
+
+ if wd.trim() == "q" {
+ break;
+ }
+
+ hash.entry(wd).or_insert_with(Vec::new).push((*rd.trim()).to_string());
+ }
+
+ for (k,v) in &hash {
+ println!("{k} {:?}", v);
+ }
+}