Problem Solving with Go course

ComplexityCount the Groups, Not the Items

Problem Solving with Go

Display

Theme

Complexity · Test exercise

Count the Groups, Not the Items

This is the classic "part two explodes" pattern. Part one asks for the result after 10 steps, and an ordinary simulation feels fine. Part two asks for 50 steps, and the number of things doubles over and over. After 50 steps there are more than a quadrillion of them. A slice with one element per thing will never fit in memory.

Identical things don't need storing one by one

Look at the question. Puzzles rarely care which item is which. Usually they only ask how many of each kind there are. If every blue sheet behaves the same way, one number is enough: how many blue sheets there are.

// one entry per sheet: grows without limit
sheets := []string{"blue", "red", "red", "green", ...}

// one number per colour: always three entries
counts := map[string]int{"blue": 4, "red": 0, "green": 1}

Each step, every colour adds to its new colours as many sheets as it has:

next := make(map[string]int)
for colour, n := range counts {
	for _, becomes := range rules[colour] {
		next[becomes] += n // n sheets at once, not one at a time
	}
}
counts = next

The work per step is now proportional to the number of kinds, not the number of items. 50 steps with three colours means a few hundred operations, not quadrillions.

Still use a new map every step

Just like a grid simulation: every sheet changes at once. Write the result into next, not into the counts you're reading. Otherwise a sheet that just turned red changes again in the same step.

Watch the size of int

In Go, an int on a 64-bit computer holds up to about 9.2 × 10¹⁸. The numbers in this lesson still fit. If a puzzle talks about counts far bigger than that, check whether your results start going negative or wrapping around: that's a sign of overflow.

Task

An origami workshop has a strange rule. Every hour, every sheet of paper changes:

ColourBecomes
bluetwo red and one green
redtwo blue
greenstays one green

The rule is already in the rules map.

  1. Complete after(start map[string]int, hours int) map[string]int: how many sheets of each colour there are after hours hours, starting from start. Keep one number per colour. Don't change the start map.
  2. Complete total(counts map[string]int) int: the total number of sheets.

The tests compare your result with a one-by-one simulation for the first hours, then ask for the result after 50 hours.

main.go
package main

import (
	"fmt"
	"slices"
)

// rules says what one sheet of each colour turns into after one hour.
var rules = map[string][]string{
	"blue":  {"red", "red", "green"},
	"red":   {"blue", "blue"},
	"green": {"green"},
}

// after returns how many sheets of each colour there are after the given hours.
// It keeps one count per colour instead of one entry per sheet.
func after(start map[string]int, hours int) map[string]int {
	// TODO: one map of counts per hour, never a slice with one entry per sheet
	return start
}

// total adds up every colour.
func total(counts map[string]int) int {
	// TODO
	return 0
}

func main() {
	for _, hours := range []int{1, 2, 10, 50} {
		counts := after(map[string]int{"blue": 1}, hours)
		colours := make([]string, 0, len(counts))
		for c := range counts {
			colours = append(colours, c)
		}
		slices.Sort(colours)
		fmt.Printf("after %d hours: %d sheets", hours, total(counts))
		for _, c := range colours {
			fmt.Printf(", %s %d", c, counts[c])
		}
		fmt.Println()
	}
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)