From 0f5c6610e691c4126e8f6684b1056bfd8711d28c Mon Sep 17 00:00:00 2001 From: Ed Guloien Date: Wed, 13 May 2026 17:48:29 -0400 Subject: [PATCH] made it a little more rust idiomatic --- src/main.rs | 57 +++++++++++++++++++++++++---------------------------- 1 file changed, 27 insertions(+), 30 deletions(-) diff --git a/src/main.rs b/src/main.rs index f347612..1ec4dc3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,15 +37,16 @@ pub fn tokenize(input: &str) -> Vec { // Since our tokenize function returns new Strings, there is not much sense in // taking &[&str] here since this would require an extra allocation to move the // string slices to a new vector. This doesn't copy heap on the way in anyway. -pub fn create_frequency_vec(input: &mut [String]) -> Vec<(String,usize)> { - // save a copy on the way in by allowing mutation of the passed input - input.sort(); // O(n log n) +pub fn create_frequency_vec(input: &[String]) -> Vec<(String,usize)> { + // perhaps unnecessary copy, but this preserves the original token list + let mut sorted = input.to_vec(); + sorted.sort(); // O(n log n) let mut counts : Vec<(String, usize)> = Vec::new(); - for w in input { // O(n) + for w in sorted { // O(n) match counts.last_mut() { - Some((last, count)) if last == w => *count += 1, - _ => counts.push((w.to_string(), 1)), + Some((last, count)) if last == &w => *count += 1, + _ => counts.push((w.clone(), 1)), } } counts.sort_by(|a,b| b.1.cmp(&a.1)); // sort by frequency, O(m log m) @@ -53,9 +54,7 @@ pub fn create_frequency_vec(input: &mut [String]) -> Vec<(String,usize)> { } pub fn analyze_word_count(input: &[(String,usize)]) -> usize { - let mut count = 0; - input.iter().for_each(|(_,c)| { count+=c }); - count + input.iter().map(|(_,c)| c).sum() } pub fn analyze_unique_word_count(input: &[(String,usize)]) -> usize { @@ -64,7 +63,7 @@ pub fn analyze_unique_word_count(input: &[(String,usize)]) -> usize { pub fn average_word_length(input: &[(String, usize)]) -> f64 { if input.is_empty() { - return 0 as f64; + return 0.0; } let mut len = 0; let mut tokens = 0; @@ -86,9 +85,7 @@ pub fn top_n_most_used(input: &[(String, usize)], n: usize) -> &[(String, usize) // todo: option pub fn longest_word(input: &[(String, usize)]) -> usize { - let mut max = 0; - input.iter().for_each(|(w,_)| if w.len() > max { max = w.len() }); - max + input.iter().map(|(w,_)| w.len()).max().unwrap_or(0) } pub fn num_digits(n: usize) -> usize { @@ -119,7 +116,7 @@ pub fn print_analysis(input: &[(String, usize)]) { println!("{: