Skip to content

Checkpoint: List Open Tasks in Order

The Course
•
24 min study
Exercise

Your turn

Given a map from task IDs to done flags, write openIDs to return only the unfinished IDs in sorted order. Check a mixed map and an empty map.

Your working space Go
package main

func main() {
	// Build your solution here.
}
Hint 1: the idea

Filter while collecting IDs and sort only the resulting slice.

Hint 2: a first step

Append an ID when its done flag is false.

Worked solution
Run the solution Go
package main

import (
	"fmt"
	"slices"
)

func openIDs(tasks map[int]bool) []int {
	ids := []int{}
	for id, done := range tasks {
		if !done {
			ids = append(ids, id)
		}
	}
	slices.Sort(ids)
	return ids
}

func main() {
	fmt.Println(openIDs(map[int]bool{9: false, 1: true, 3: false}))
	fmt.Println(openIDs(nil))
}
Text
[3 9]
[]

Starting from []int{} rather than a nil slice makes no difference to the printout, but it shows the empty result is intended. Ranging over a nil map is safe.

Was this article helpful?

Your response is saved on this device.