Problem Solving with Go course

Maps and SetsGrouping with map[K][]V

Problem Solving with Go

Display

Theme

Maps and Sets · Output exercise

Grouping with map[K][]V

Sometimes you don't need a count but a list per group: every item on a shelf, every order from a customer, every neighbour of a point. The shape is a map whose values are slices:

shelves := make(map[string][]string)
shelves["B3"] = append(shelves["B3"], "hammer")

Appending to nil is safe: a missing key reads as a nil slice, and append makes a new one. So there's no need to check whether the key exists yet.

Output you can count on

Printing a map directly gives a random order, and an output exercise compares every character. For the same output on every run:

  1. collect the keys into a slice and sort it with slices.Sort;
  2. sort each group's items too if their order matters.

Dropping duplicates from a sorted slice

After sorting, equal values sit next to each other. slices.Compact removes every value that equals the one just before it:

items := []string{"hammer", "chisel", "hammer"}
slices.Sort(items)              // [chisel hammer hammer]
items = slices.Compact(items)   // [chisel hammer]

Store the result back in the variable: Compact returns a shorter slice. Another way is the set from the previous lesson, then sorting its keys.

Task

A tool store logs what's on its shelves, one item per line: <shelf> <item>. Item names can be several words long, and some items are logged twice. The starter code already groups the items by shelf.

Print every shelf in alphabetical order of the shelf name, one line per shelf:

<shelf>: <item>, <item>, ...

The items on each shelf are in alphabetical order, without duplicates, joined with ", " (strings.Join). The output must match the expected output exactly.

main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	shelves := make(map[string][]string) // shelf → items on it

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		shelf, item, found := strings.Cut(strings.TrimSpace(scanner.Text()), " ")
		if !found {
			continue
		}
		shelves[shelf] = append(shelves[shelf], item)
	}

	// TODO: print the shelves in alphabetical order, each as
	// "<shelf>: <items>", with the items sorted, without repeats, joined by ", "
	for shelf, items := range shelves {
		fmt.Println(shelf, items)
	}
}
Go runtime not loaded yet

9 lines · 91 B of the 1 MB limit. Submit always uses the lesson's own input.