I want to grouping strings with the same composition using Go.
Let's say I have array of string like this:
['kita', 'atik', 'tika', 'aku', 'kia', 'makan', 'kua']
and the expected output is like this
[
["kita", "atik", "tika"],
["aku", "kua"],
["makan"],
["kia"]
]
This should be doable using maps:
package main
import (
"log"
"sort"
)
func main() {
words := []string{"kita", "atik", "tika", "aku", "kia", "makan", "kua"}
refs := map[string][]string{}
for _, word := range words {
// normalizing word
r := []rune(word)
sort.Slice(r, func(i, j int) bool { return r[i] < r[j] })
sortedWord := string(r)
// appending in the normalized word map
refs[sortedWord] = append(refs[sortedWord], word)
}
// transforming into a slice of slices
result := [][]string{}
for _, item := range refs {
result = append(result, item)
}
log.Println(result)
}