From c5fb6a609b0b315241bf53d6c3a822127c09da36 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Fri, 20 Jul 2018 00:08:19 +0300 Subject: Change: print only the 10 most common words --- src/main.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 4045cd7..2162453 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,7 +12,7 @@ fn main() -> io::Result<()> { let mut f = File::open(&filename)?; let mut reader = io::BufReader::new(f); let counts = count_words(&mut reader)?; - counts.print() + counts.print(10) } Ok(()) } @@ -69,8 +69,17 @@ impl WordCounts { *counter += count; } - fn print(&self) { + fn print(&self, max: usize) { + let mut top = Vec::new(); for (word, count) in self.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); } } -- cgit v1.2.1