From 5085af39dae3d3d5c4a1fe523bfe881d6df1e4b8 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Tue, 24 Jul 2018 15:55:44 +0300 Subject: Change: use iterators a lot --- src/counts.rs | 19 +++---------------- src/main.rs | 24 +++--------------------- 2 files changed, 6 insertions(+), 37 deletions(-) diff --git a/src/counts.rs b/src/counts.rs index a339eb3..b7c4352 100644 --- a/src/counts.rs +++ b/src/counts.rs @@ -5,28 +5,15 @@ 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() { + 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); } } diff --git a/src/main.rs b/src/main.rs index f0fd9ae..76d4568 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,27 +21,9 @@ fn count_words(reader: &mut io::BufReader) -> io::Result { 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(); - } + for w in line.split(|c: char| !c.is_alphabetic()).filter(|w| !w.is_empty()) { + count(&mut counts, w.to_lowercase().clone()); } } - if !word.is_empty() { - count(&mut counts, word.clone()); - } - counts + Ok(counts) } -- cgit v1.2.1