summaryrefslogtreecommitdiff
path: root/src/counts.rs
blob: b7c435291a978f7a4023d0b574d8580fc78e9a83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::collections::HashMap;
pub type WordCounts = HashMap<String, u32>;

pub fn count(counts: &mut WordCounts, word: String) {
    add(counts, word, 1);
}

pub fn add(counts: &mut WordCounts, word: String, count: u32) {
    let counter = counts.entry(word).or_insert(0);
    *counter += count;
}

pub fn print(counts: &WordCounts, max: usize) {
    let mut counts: Vec<_> = counts.iter().map(|(w,c)| (c,w)).collect();
    counts.sort();
    for (count, word) in counts.into_iter().rev().take(max) {
        println!("{} {}", count, word);
    }
}