small (but useful) optimization to is_anagram
checking length avoids sorting in many cases
This commit is contained in:
parent
9f22e75549
commit
b32d0465ea
1 changed files with 10 additions and 1 deletions
11
src/main.rs
11
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 {
|
fn is_anagram(word: &str) -> impl std::ops::FnMut(&&String) -> bool {
|
||||||
// filtro
|
// filtro
|
||||||
let sorted_word = sort_word(line_to_word(word).as_str()).unwrap();
|
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 }}}
|
// filtri }}}
|
||||||
|
|
Reference in a new issue