Course of Raku / Addendum 🆕 / Bringing it together / Mixed mini-projects / Exercises / Group the anagrams

Solution: Group the anagrams

Here is a possible solution to the task.

Code

my @words = <listen silent enlist cat act dog>;
my %groups;

for @words -> $word {
    %groups{ $word.comb.sort.join }.push($word);
}

for %groups.sort(*.key) -> $pair {
    say $pair.value.sort.join(' ');
}

🦋 You can find the source code in the file anagram-groups.raku.

Output

act cat
dog
enlist listen silent

Comments

  1. Sorting a word’s letters gives a canonical key: all anagrams share the same sorted letters, so pushing onto %groups{ ... } gathers them under one key.

  2. Each hash value is the list of words in that group, printed alphabetically with .sort.join.

Course navigation

Group the anagrams   |   Sieve of Eratosthenes