Problem Solving with Go course

Recursion and DPMemoization

Problem Solving with Go

Display

Theme

Recursion and DP · Test exercise

Memoization

Recursion has a dark side. Count the ways to lay a garden path of length n with slabs of length 1 and 2: the first slab is a 1 (then lay the remaining n-1) or a 2 (then lay the remaining n-2).

func ways(n int) int {
	if n == 0 {
		return 1
	}
	total := ways(n - 1)
	if n >= 2 {
		total += ways(n - 2)
	}
	return total
}

It's correct, and for n = 50 it never finishes. ways(50) calls ways(49) and ways(48). ways(49) calls ways(48) again, and ways(47). The same small questions are answered over and over: the number of calls grows like the answer itself, into the billions.

Remember every answer

ways(48) always returns the same number, so compute it once and keep it. That's memoization: before working, look in a map; after working, store the answer.

memo := map[int]int{}
var ways func(n int) int
ways = func(n int) int {
	if n == 0 {
		return 1
	}
	if v, ok := memo[n]; ok {
		return v
	}
	total := 0
	// ...the same recursion as before...
	memo[n] = total
	return total
}

Now each n is worked out only once, so ways(50) needs about 50 calculations instead of billions. The recursion still reads like the problem; only the map is new.

A recursive closure

A closure that calls itself must be declared before it's assigned: var ways func(n int) int first, then ways = func.... With ways := func... the name doesn't exist yet inside the function body, and Go reports an error.

Declaring the memo next to the closure, inside the outer function, gives every call of the outer function a fresh map. A memo shared between calls with different slab sizes would hand back wrong answers.

Task

This lesson's input has one path per line: the length, a colon, and the slab sizes allowed.

Complete patterns(n int, sizes []int) int: how many ways a path of length n can be laid with slabs of the given sizes, one after another. Order matters, so 1+2 and 2+1 are different patterns. An empty path (n == 0) has exactly one pattern, and every size is at least 1. The tests go up to n = 80, so remember your answers.

main.go
package main

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

// patterns returns how many ways a path of length n can be laid with slabs of the
// given sizes, one after another. Order matters: 1+2 and 2+1 are different patterns.
// An empty path (n == 0) has exactly one pattern.
func patterns(n int, sizes []int) int {
	// TODO: a recursive closure on the length still left, remembered in a map[int]int
	return 0
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		length, list, ok := strings.Cut(scanner.Text(), ":")
		n, err := strconv.Atoi(strings.TrimSpace(length))
		if !ok || err != nil {
			continue
		}
		var sizes []int
		for _, f := range strings.Fields(list) {
			if s, err := strconv.Atoi(f); err == nil {
				sizes = append(sizes, s)
			}
		}
		fmt.Printf("length %d with slabs %v: %d patterns\n", n, sizes, patterns(n, sizes))
	}
}
Go runtime not loaded yet

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