From b32d0465ea81ca81a09e2524c4f39ce41208978e Mon Sep 17 00:00:00 2001 From: boyska Date: Tue, 19 May 2020 11:28:30 +0200 Subject: [PATCH] small (but useful) optimization to is_anagram checking length avoids sorting in many cases --- src/main.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 13dac1d..9464066 100644 --- a/src/main.rs +++ b/src/main.rs @@ -90,7 +90,16 @@ fn sort_word(word: &str) -> Result { fn is_anagram(word: &str) -> impl std::ops::FnMut(&&String) -> bool { // filtro let sorted_word = sort_word(line_to_word(word).as_str()).unwrap(); - move |w| sorted_word == sort_word(w.as_str()).unwrap() + move |w| { + if sorted_word.len() != w.len() { + // this check doesn't add any correctness to the algorithm, but + // is a small optimization: avoids sorting w if the length is different + false + } else { + let sorted_other = sort_word(w.as_str()).unwrap(); + sorted_word == sorted_other + } + } } // filtri }}}