[Beginner] Improvements to anagram searching function (exercism)

⚓ Rust    📅 2026-06-29    👤 surdeus    👁️ 2      

surdeus

This is an easy problem from exercism; it's about finding out which candidate words are anagrams of a "reference word".

It passes all tests. The idea is to convert the words into HashMaps, to take advantage of the comparison allowed between them.

One current issue is that &cand.to_lowercase() is repeated.

One possible issue is that filter is used several times for readability, which may be wrong.

use std::collections::{HashMap, HashSet};

/// Puts all true anagrams of `word` into a HashSet.
pub fn anagrams_for<'a>(word: &'a str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
    let lw_word = word.to_lowercase();
    let word_hm = letter_count(&lw_word);
    let mut out = HashSet::new();

    possible_anagrams
        .iter()
        .filter(|cand| cand.len() == word.len())
        .filter(|cand| lw_word.ne(&cand.to_lowercase()))
        .for_each(|cand| {
            let candidate_hm = letter_count(&cand.to_lowercase());
            if word_hm.eq(&candidate_hm) {
                out.insert(*cand);
            }
        });

    out
}

/// Convert word into a HashMap of character-count.
/// We don't need i32 because HashMaps can be compared!
fn letter_count(word: &str) -> HashMap<char, u32> {
    let mut count = HashMap::new();
    word.chars().for_each(|c| {
        let v = count.entry(c).or_insert(0);
        *v += 1
    });
    count
}

2 posts - 2 participants

Read full topic

🏷️ Rust_feed