Last active
August 29, 2015 14:01
-
-
Save schmee/b490b807b53e99346cd1 to your computer and use it in GitHub Desktop.
This file contains 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
extern crate collections; | |
use collections::HashMap; | |
use std::hash::Hash; | |
fn main() { | |
let mut map: CountedSet<&'static str> = CountedSet::new(); | |
let strings = ["a", "b", "a", "b", "b", "c"]; | |
let answer = [("b", 3u), ("a", 2), ("c", 1)]; | |
for k in strings.iter() { | |
map.add(*k); | |
} | |
assert!(answer == map.most_common(3).as_slice()) | |
} | |
} | |
struct CountedSet<T> { | |
data: HashMap<T, uint> | |
} | |
impl<T: Hash + TotalEq> CountedSet<T> { | |
fn add<'a>(&'a mut self, k: T) -> &'a mut uint { | |
self.data.insert_or_update_with(k, 1u, |_, v| *v += 1) | |
} | |
fn most_common<'a>(&'a self, n: uint) -> Vec<(&'a T, &'a uint)> { | |
let mut v = self.data.iter().collect::<Vec<(&T, &uint)>>(); | |
v.sort_by(|&(_, a), &(_, b)| b.cmp(a)); | |
v | |
} | |
fn new() -> CountedSet<T> { | |
CountedSet{data: HashMap::new()} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment