Browse Source

small (but useful) optimization to is_anagram

checking length avoids sorting in many cases
boyska 3 years ago
parent
commit
b32d0465ea
1 changed files with 10 additions and 1 deletions
  1. 10 1
      src/main.rs

+ 10 - 1
src/main.rs

@@ -90,7 +90,16 @@ fn sort_word(word: &str) -> Result<String, impl std::error::Error> {
 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 }}}