Problem Solving with Go course

Recursion and DPRecursion

Problem Solving with Go

Display

Theme

Recursion and DP · Test exercise

Recursion

A function that calls itself is recursive. It sounds circular, but it's the most natural way to handle anything built from smaller copies of itself: a folder full of folders, a team made of smaller teams, a puzzle that splits into smaller puzzles.

Two parts

Every recursive function has:

  1. a base case, small enough to answer directly, without calling itself;
  2. a recursive case, which answers by calling itself on something smaller and combining the results.
// size of a folder: its own files plus every folder inside it
func folderSize(f Folder) int {
	total := f.Files // when there are no subfolders, this is the answer
	for _, sub := range f.Subfolders {
		total += folderSize(sub)
	}
	return total
}

Here the base case hides in the loop: a folder without subfolders doesn't loop at all and returns its own files. Each call works on a smaller part of the tree, so the calls always reach the bottom.

Trust the smaller call

The trick to writing recursion is not to trace every call in your head. Assume the call on the smaller part already returns the right answer, and ask only: how do I build my answer from those? "My team is me plus my reports' teams." "My depth is one more than my deepest report's."

Searching with recursion

Recursion can also look for something and report the way to it. Return a result that says "not found" (such as nil), and when a smaller call does find it, add the current step in front:

if rest := chain(reports, r, name); rest != nil {
	return append([]string{top}, rest...)
}

Each call that waits keeps a little memory until it returns. Trees in puzzles are usually shallow enough; for a long chain, such as a path through a large grid, a loop with a stack (the previous chapter) is safer.

Task

This lesson's input is an organisation chart: each line is a manager, a colon, and the people who report to them. The first line names the head of the organisation. reports maps a name to their direct reports; someone with no line has no reports.

  1. Complete teamSize(reports, name) int: name plus everyone below them, at any level.
  2. Complete depth(reports, name) int: how many levels the team has. Someone with no reports has a depth of 1.
  3. Complete chain(reports, top, name) []string: the people from top down to name, both included, or nil when name is not in top's team.
main.go
package main

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

// teamSize returns how many people are in name's team: name and everyone below them.
func teamSize(reports map[string][]string, name string) int {
	// TODO: 1 for name, plus the team size of each direct report
	return 0
}

// depth returns how many levels name's team has. Someone with no reports is 1 level.
func depth(reports map[string][]string, name string) int {
	// TODO
	return 0
}

// chain returns the people from top down to name, both included, or nil when name
// is not in top's team.
func chain(reports map[string][]string, top, name string) []string {
	// TODO: the base case is top == name
	return nil
}

func main() {
	reports := map[string][]string{}
	top := ""
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		boss, team, ok := strings.Cut(scanner.Text(), ":")
		if !ok {
			continue
		}
		boss = strings.TrimSpace(boss)
		if top == "" {
			top = boss // the first line names the head of the organisation
		}
		reports[boss] = append(reports[boss], strings.Fields(team)...)
	}
	fmt.Println("people:", teamSize(reports, top))
	fmt.Println("levels:", depth(reports, top))
	fmt.Println("from the top to fay:", chain(reports, top, "fay"))
}
Go runtime not loaded yet

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