summaryrefslogtreecommitdiff
path: root/src/counts.rs
blob: a339eb3829913c3457bd7a19a679b642d050af40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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(counts: &mut WordCounts, other: &WordCounts) {
    for (word, count) in other.iter() {
        add(counts, word.to_string(), *count);
    }
}

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 top = Vec::new();
    for (word, count) in counts.iter() {
        top.push((count, word));
        if top.len() > max {
            top.sort();
            top.reverse();
            top.truncate(max);
        }
    }
    for (count, word) in top.iter() {
        println!("{} {}", count, word);
    }
}