use std::{collections::HashMap, hash::Hash};
pub struct Counter<K> {
counts: HashMap<K, usize>,
}
impl<K> Counter<K>
where
K: Eq + Hash,
{
pub fn new() -> Self {
Counter {
counts: HashMap::new(),
}
}
pub fn get(&self, key: &K) -> usize {
*self.counts.get(key).unwrap_or(&0)
}
pub fn increment(&mut self, key: K) {
*self.counts.entry(key).or_insert(0) += 1;
}
pub fn reset(&mut self, key: K) {
self.counts.insert(key, 0);
}
pub fn clear(&mut self) {
self.counts.clear();
}
pub fn total(&self) -> usize {
self.counts.values().sum()
}
pub fn mostcommon(&self, n: usize) -> Vec<(&K, usize)> {
let mut counts_vec: Vec<(&K, usize)> = self.counts.iter().map(|(k, &v)| (k, v)).collect();
counts_vec.sort_by(|a, b| b.1.cmp(&a.1));
counts_vec.into_iter().take(n).collect()
}
}