Problem Solving with Go course

Recursion and DPBottom-Up Tables

Problem Solving with Go

Display

Theme

Recursion and DP · Test exercise

Bottom-Up Tables

Memoization works from the top: ask the big question, and the recursion asks the smaller ones it needs. Dynamic programming (DP) can also run the other way, from the bottom: answer the smallest questions first, in a table, so every bigger answer finds what it needs already filled in.

The same idea, as a loop

Take the cheapest way to buy exactly x litres of paint. The last can in the basket is one of the sizes on sale, so:

best[x] = the lowest of  best[x - size] + price   for every can that fits
best[0] = 0              (nothing to buy)

best[x] only needs entries for smaller amounts. So fill the table from 0 upwards, and every entry you need is already there:

best := make([]int, n+1) // best[0] is 0
for x := 1; x <= n; x++ {
	best[x] = -1 // not possible, until a can proves otherwise
	for _, c := range cans {
		// try c as the last can: best[x-c.Litres] + c.Price
	}
}

No recursion, no map: a slice indexed by the amount, and a loop in the right order. For many puzzles this is the simplest DP to write once you know the formula.

Marking "not possible"

Some amounts can't be made at all: with only 2- and 5-litre cans there's no way to get exactly 3 litres. Mark those entries with a value that can't be a real answer, such as -1, and skip them when building bigger entries. Forgetting this check is the classic DP bug: -1 + price quietly turns "impossible" into a cheap-looking number.

Top-down or bottom-up?

Memoised recursionBottom-up table
Reads likethe problema formula
Works outonly the states it needsevery state up to n
Storagea mapa slice (or a 2D slice)
Deep recursionpossiblenever

Both give the same answers. Start with whichever you can write correctly; switch when the other one is clearly simpler.

Task

This lesson's input says how much paint is needed, then lists the cans on sale: litres and price. There is at least one can, and every can holds at least 1 litre.

  1. Complete costTable(cans []Can, upTo int) []int: entries 0 to upTo, where entry x is the lowest price for exactly x litres, or -1 when no mix of cans makes exactly x.
  2. Complete cheapest(cans []Can, litres int) (int, bool): the lowest price for exactly litres, and false when it can't be done.
  3. Complete cheapestAtLeast(cans []Can, litres int) int: the lowest price for at least litres. Leftover paint is fine. Hint: buying more than litres + biggest - 1 litres (with biggest the largest can) never helps, because one can could be left out.
main.go
package main

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

// Can is a size of paint can on sale: how many litres it holds and what it costs.
type Can struct {
	Litres, Price int
}

// costTable returns best where best[x] is the lowest price for exactly x litres,
// or -1 when no mix of cans makes exactly x, for every x from 0 to upTo.
func costTable(cans []Can, upTo int) []int {
	// TODO: best[0] is 0; fill best[1], best[2], ... from the entries before them
	return make([]int, upTo+1)
}

// cheapest returns the lowest price for exactly litres litres, and false when no
// mix of cans adds up to exactly that.
func cheapest(cans []Can, litres int) (int, bool) {
	// TODO
	return 0, false
}

// cheapestAtLeast returns the lowest price for at least litres litres. There is at
// least one can, and every can holds at least 1 litre.
func cheapestAtLeast(cans []Can, litres int) int {
	// TODO: a bigger table, then the lowest price from best[litres] on
	return 0
}

func main() {
	need := 0
	var cans []Can
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) != 2 {
			continue
		}
		b, err := strconv.Atoi(f[1])
		if err != nil {
			fmt.Println("bad line:", scanner.Text())
			return
		}
		if f[0] == "need" {
			need = b
			continue
		}
		a, err := strconv.Atoi(f[0])
		if err != nil {
			fmt.Println("bad line:", scanner.Text())
			return
		}
		cans = append(cans, Can{a, b})
	}
	if cost, ok := cheapest(cans, need); ok {
		fmt.Printf("exactly %d litres: %d\n", need, cost)
	} else {
		fmt.Printf("exactly %d litres: not possible\n", need)
	}
	fmt.Printf("at least %d litres: %d\n", need, cheapestAtLeast(cans, need))
}
Go runtime not loaded yet

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