diff options
Diffstat (limited to 'src/counts.rs')
-rw-r--r-- | src/counts.rs | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/src/counts.rs b/src/counts.rs new file mode 100644 index 0000000..a339eb3 --- /dev/null +++ b/src/counts.rs @@ -0,0 +1,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); + } +} |