Last active
November 4, 2022 03:15
-
-
Save mykhailokrainik/0d893406068a6a9eb8f2284b678de4f7 to your computer and use it in GitHub Desktop.
Find 3 most popular keywords from user search history #hash #rust #search
This file contains hidden or 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 std::collections::HashMap; | |
const TOP_COUNT: usize = 3; | |
type CountMap<'a> = HashMap<&'a str, usize>; | |
fn worlds_count<'a>(query: &'a str, keys: &mut CountMap<'a>) { | |
let words = query.split(" ").map(|c| c.trim()).collect::<Vec<_>>(); | |
for w in words { | |
if keys.contains_key(&w) { | |
*keys.entry(&w).or_insert(0) += 1; | |
} | |
} | |
} | |
fn top_search<'a, const D: usize>(words: CountMap<'a>) -> Vec<&'a str> { | |
let top: &mut [(&str, usize); D] = &mut [("", 0usize); D]; | |
for (k, v) in words { | |
let mut kv = (k, v); | |
'sort: for i in 0..top.len() { | |
if kv.1 > top[i].1 { | |
let tmp = top[i]; | |
top[i] = kv; | |
kv = tmp; | |
continue 'sort; | |
} | |
} | |
} | |
top.into_iter().map(|(words, _)| *words).collect() | |
} | |
fn main() {} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn it_worlds_count() { | |
let mut keys = keywords(&["iphone", "samsung", "motorola", "siemens", "nokia"]); | |
worlds_count("compare iphone vs samsung", &mut keys); | |
worlds_count("is iphone is best choice", &mut keys); | |
worlds_count("motorola smartphones 2022", &mut keys); | |
worlds_count("why samsung note is worth", &mut keys); | |
worlds_count("should I change my iphone", &mut keys); | |
worlds_count("iphone release date", &mut keys); | |
worlds_count("flagman samsung release date", &mut keys); | |
worlds_count("new motorola release date", &mut keys); | |
worlds_count("what happend with nokia", &mut keys); | |
assert_eq!( | |
keys, | |
HashMap::from([ | |
("siemens", 0), | |
("nokia", 1), | |
("motorola", 2), | |
("samsung", 3), | |
("iphone", 4) | |
]) | |
); | |
let top3 = top_search::<TOP_COUNT>(keys); | |
assert_eq!(top3, vec!["iphone", "samsung", "motorola"]); | |
} | |
fn keywords<'a>(keys: &'a [&'a str]) -> CountMap<'a> { | |
let mut h: CountMap = HashMap::new(); | |
keys.into_iter().for_each(|k| { | |
h.insert(k, 0usize); | |
}); | |
h | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment