small (but useful) optimization to is_anagram

checking length avoids sorting in many cases
This commit is contained in:
boyska 2020-05-19 11:28:30 +02:00
parent 9f22e75549
commit b32d0465ea

View file

@ -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 }}}