Go: Group the anagrams

A map of slices groups items under a shared key.

What to build

A program that puts words made of the same letters into groups.

Requirements

  • Read n, then n lower case words.
  • Two words belong to the same group if they have the same letters (for example listen and silent).
  • Print each group on one line: its words in alphabetical order, separated by spaces (repeated words stay repeated).
  • Print the groups ordered by their first word.

Input

Line 1: n. Then n words.

Output

One line per group.

Constraints

1 ≤ n ≤ 50; words have 1 to 10 lower case letters.

Example

Input:

6
listen silent enlist google gogole cat

Output:

cat
enlist listen silent
gogole google

Why it works

Words that are anagrams have the same letters once sorted, so the sorted letters make a good key. Sorting the words of each group and the groups themselves removes the random map order.

Examples

Example 1 · Input
6
listen silent enlist google gogole cat
Expected output
cat
enlist listen silent
gogole google
Example 2 · Input
4
act cat tac dog
Expected output
act cat tac
dog

Hints

Hint 1

The key of a group is the word's letters in sorted order: convert to a []byte and sort it with sort.Slice.

Hint 2

Use a map[string][]string, then sort the words in each group and sort the groups by their first word.

Solution

Show one correct solution (try it yourself first)
package main

import (
	"fmt"
	"sort"
	"strings"
)

func key(w string) string {
	b := []byte(w)
	sort.Slice(b, func(i, j int) bool { return b[i] < b[j] })
	return string(b)
}

func main() {
	var n int
	fmt.Scan(&n)
	groups := make(map[string][]string)
	for i := 0; i < n; i++ {
		var w string
		fmt.Scan(&w)
		k := key(w)
		groups[k] = append(groups[k], w)
	}
	list := [][]string{}
	for _, g := range groups {
		sort.Strings(g)
		list = append(list, g)
	}
	sort.Slice(list, func(i, j int) bool { return list[i][0] < list[j][0] })
	for _, g := range list {
		fmt.Println(strings.Join(g, " "))
	}
}

▶ Open this solution in the compiler

Lesson: Maps →