How to convert a slice of strings and group all the anagrams into subslices in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "sort"
)

// groupAnagrams groups an array of strings into subarrays of anagrams.
func groupAnagrams(words []string) [][]string {
    anagramMap := make(map[string][]string)

    for _, word := range words {
        // Sort the characters in the word to create a key
        sorted := sortString(word)

        // Append the word to the group identified by the sorted key
        anagramMap[sorted] = append(anagramMap[sorted], word)
    }

    // Collect the grouped anagrams into a slice of slices
    result := make([][]string, 0, len(anagramMap))
    for _, group := range anagramMap {
        result = append(result, group)
    }

    return result
}

// sortString returns a string with its characters sorted alphabetically
func sortString(s string) string {
    runes := []rune(s)
    
    sort.Slice(runes, func(i, j int) bool {
        return runes[i] < runes[j]
    })
    
    return string(runes)
}

func main() {
    words := []string{"eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"}
    result := groupAnagrams(words)

    fmt.Println("Grouped anagrams:")
    for _, group := range result {
        fmt.Println(group)
    }
}



/*
run:

Grouped anagrams:
[eat tea ate]
[rop orp pro]
[nat tan]
[bat]

*/

 



answered 17 hours ago by avibootz
...