use std::collections::HashMap;
use std::hash::Hash;
/// Counter๋ ๊ฐ T ํ์
๊ฐ์ด ํ์๋ ํ์๋ฅผ ๊ณ์ฐํฉ๋๋ค.
struct Counter<T: Eq + Hash> {
values: HashMap<T, u64>,
}
impl<T: Eq + Hash> Counter<T> {
/// ์ Counter๋ฅผ ๋ง๋ญ๋๋ค.
fn new() -> Self {
Counter { values: HashMap::new() }
}
/// ์ง์ ๋ ๊ฐ์ ๋ฐ์ ํ์๋ฅผ ์
๋๋ค.
fn count(&mut self, value: T) {
*self.values.entry(value).or_default() += 1;
}
/// ์ง์ ๋ ๊ฐ์ด ํ์๋ ํ์๋ฅผ ๋ฐํํฉ๋๋ค.
fn times_seen(&self, value: T) -> u64 {
self.values.get(&value).copied().unwrap_or_default()
}
}
fn main() {
let mut ctr = Counter::new();
ctr.count(13);
ctr.count(14);
ctr.count(16);
ctr.count(14);
ctr.count(14);
ctr.count(11);
for i in 10..20 {
println!("{} ๊ฐ์ {} ๊ฐ์ ๋ฐ๊ฒฌํ์ต๋๋ค.", ctr.times_seen(i), i);
}
let mut strctr = Counter::new();
strctr.count("์ฌ๊ณผ");
strctr.count("์ค๋ ์ง");
strctr.count("์ฌ๊ณผ");
println!("์ฌ๊ณผ {}๊ฐ ๋ฐ์", strctr.times_seen("์ฌ๊ณผ"));
}