Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find 3 most popular keywords from user search history #hash #rust #search
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