Anagram Groups By Sorted Key
Group anagrams by their sorted rune key so listen, silent, and enlist share one map entry, with sorted keys keeping printed output deterministic.
Code
package main
import (
"fmt"
"sort"
"strings"
)
func anagramKey(word string) string {
runes := []rune(word)
sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })
return string(runes)
}
func main() {
words := []string{"listen", "silent", "enlist", "google", "banana"}
groups := make(map[string][]string)
for _, w := range words {
key := anagramKey(w)
groups[key] = append(groups[key], w)
}
sortedKeys := make([]string, 0, len(groups))
for key := range groups {
sortedKeys = append(sortedKeys, key)
}
sort.Strings(sortedKeys)
for _, key := range sortedKeys {
fmt.Printf("%s -> %s\n", key, strings.Join(groups[key], ", "))
}
}Anagram Groups By Sorted Key: how the code works
Anagram Groups By Sorted Key comes down to the functions anagramKey and main.
A single loop drives the file — for _, w := range words.
What to watch for
- Imports stay inside the standard library — nothing to install.
Using it
Signature: func anagramKey(word string) string
Running the file executes main, which drives anagramKey in order.
Key statements
sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })
for _, key := range sortedKeys {
fmt.Printf("%s -> %s\n", key, strings.Join(groups[key], ", "))
}
for _, w := range words {
key := anagramKey(w)
groups[key] = append(groups[key], w)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Anagram Groups By Sorted Key?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.