Problem Solving with Go course

Maps and SetsSets with map[T]struct{}

Problem Solving with Go

Display

Theme

Maps and Sets · Test exercise

Sets with map[T]struct{}

Go has no built-in set type. The stand-in is a map whose keys are the set's members and whose values go unused:

seen := make(map[string]struct{})
seen["heron"] = struct{}{} // add a member

if _, ok := seen["heron"]; ok {
	fmt.Println("seen it before")
}
delete(seen, "heron") // remove a member
fmt.Println(len(seen)) // number of members

struct{} is a type with no fields that takes zero bytes, and struct{}{} is its only value. Plenty of people use map[string]bool instead because it reads shorter (if seen[x]). Both are fine. struct{} makes it clear that only the keys matter.

Why a set?

Checking "is x in this slice?" with a loop takes time proportional to the slice's length. In a set, the same check takes constant time on average. When you check thousands of times, the difference is big.

A set is also the easiest way to drop duplicates: put everything in, and len(set) is the number of distinct values.

Set operations

The two that come up most:

  • Intersection: values in A and in B. Build a set from B, then check every member of A.
  • Difference: values in A but not in B. The same, with the condition flipped.
inB := toSet(b)
for x := range toSet(a) {
	if _, ok := inB[x]; ok {
		// x is in both
	}
}

Iterating a set is random too, so sort the result (slices.Sort) before returning it.

Task

Ana and Budi write down the birds they spot, one line per person, separated by commas. Some birds are written down more than once.

  1. Complete toSet(xs []string) map[string]struct{}. For an empty slice, return an empty set (not nil).
  2. Complete both(a, b []string) []string: the values in a and in b, without duplicates, in alphabetical order.
  3. Complete onlyIn(a, b []string) []string: the values in a that aren't in b, without duplicates, in alphabetical order.

both and onlyIn return an empty slice (not nil) when there's nothing to return. The list function and main are ready.

main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// toSet returns the distinct values of xs as a set.
func toSet(xs []string) map[string]struct{} {
	// TODO
	return nil
}

// both returns, in alphabetical order and without repeats, the values found in a and in b.
func both(a, b []string) []string {
	// TODO
	return nil
}

// onlyIn returns, in alphabetical order and without repeats, the values in a that are not in b.
func onlyIn(a, b []string) []string {
	// TODO
	return nil
}

// list splits "a, b, c" into ["a" "b" "c"].
func list(line string) []string {
	var out []string
	for _, part := range strings.Split(line, ",") {
		if part = strings.TrimSpace(part); part != "" {
			out = append(out, part)
		}
	}
	return out
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	lines := strings.Split(strings.TrimSpace(string(data)), "\n")
	if len(lines) != 2 {
		fmt.Println("want two lines, one per birdwatcher")
		return
	}
	ana, budi := list(lines[0]), list(lines[1])
	fmt.Println("species seen by Ana:", len(toSet(ana)))
	fmt.Println("seen by both:", both(ana, budi))
	fmt.Println("only Ana:", onlyIn(ana, budi))
}
Go runtime not loaded yet

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