summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: aef750de61ca8e4607f2c3886f66d611b5807c92 (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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::env;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::collections::HashMap;



fn main() -> io::Result<()> {
    for filename in env::args().skip(1) {
        let mut f = File::open(&filename)?;
        let mut reader = io::BufReader::new(f);
        let counts = count_words(&mut reader)?;
        print(&counts, 10)
    }
    Ok(())
}


fn count_words(reader: &mut io::BufReader<File>) -> io::Result<WordCounts> {
    let mut counts = WordCounts::new();
    for line in reader.lines() {
        let line = line?;
        add_counts(&mut counts, &count_words_in_line(&line));
    }
    Ok(counts)
}


fn count_words_in_line(line: &str) -> WordCounts {
    let mut counts = WordCounts::new();
    let mut word = String::new();
    for c in line.chars() {
        if c.is_alphabetic() {
            word.push(c);
        } else {
            if !word.is_empty() {
                count(&mut counts, word.clone());
                word.clear();
            }
        }
    }
    if !word.is_empty() {
        count(&mut counts, word.clone());
    }
    counts
}


type WordCounts = HashMap<String, u32>;


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


fn add_counts(counts: &mut WordCounts, other: &WordCounts) {
    for (word, count) in other.iter() {
        add(counts, word.to_string(), *count);
    }
}


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

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);
    }
}