Problem Solving with Go course

Capstone PuzzlesStage Build, Part 2

Problem Solving with Go

Display

Theme

Capstone Puzzles · Test exercise

Stage Build, Part 2

The crew lead pins your finish time to the notice board. Then the questions start: "Can the sound team arrive two hours late?" "Is it a problem if the roof takes an extra hour?"

The puzzle, continued

Some tasks have room to spare. In the small plan from part 1, power is done at hour 1 but lights can't use it before hour 10, so power could finish as late as hour 10 and the stage would still be ready at hour 13. That room is the task's slack: 9 hours.

Other tasks have none. If roof finishes even one hour late, lights starts late, and the whole plan slips. Tasks with zero slack are called critical.

For every task in the full plan, how many hours of slack does it have, and which tasks are critical?

Think about it from the end. The last tasks must be finished by the finish time from part 1. A task must be finished early enough for every task waiting for it to start in time.

Task

Your part 1 code is already there.

  1. Complete slack(tasks map[string]Task) (map[string]int, error): for every task, how many hours later than its earliest end it can finish without making the whole stage later.
  2. Complete critical(tasks map[string]Task) ([]string, error): the tasks with no slack, sorted A to Z.

Return part 1's errors for plans that can't be built.

main.go
package main

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

// Task is one job in building the stage: how many hours it takes, and the tasks
// that must be finished before it can start.
type Task struct {
	Name  string
	Hours int
	After []string
}

// parseTask reads a line such as "lights 3: roof power": the name, the hours (1 or
// more), a colon, then the tasks it waits for (possibly none).
func parseTask(line string) (Task, error) {
	head, after, ok := strings.Cut(line, ":")
	f := strings.Fields(head)
	if !ok || len(f) != 2 {
		return Task{}, fmt.Errorf("bad task %q", line)
	}
	hours, err := strconv.Atoi(f[1])
	if err != nil || hours < 1 {
		return Task{}, fmt.Errorf("bad hours in %q", line)
	}
	return Task{f[0], hours, strings.Fields(after)}, nil
}

// earliestEnds returns, for every task, the earliest hour it can be finished when
// there are enough people to work on every task that is ready. Work starts at hour 0.
// A task that waits for a missing task, or a circle of tasks, is an error.
func earliestEnds(tasks map[string]Task) (map[string]int, error) {
	ends := map[string]int{}
	busy := map[string]bool{} // on the way down right now: seeing one again means a circle
	var end func(name string) (int, error)
	end = func(name string) (int, error) {
		if e, ok := ends[name]; ok {
			return e, nil
		}
		t, ok := tasks[name]
		if !ok {
			return 0, fmt.Errorf("unknown task %q", name)
		}
		if busy[name] {
			return 0, fmt.Errorf("tasks wait for each other in a circle at %q", name)
		}
		busy[name] = true
		start := 0
		for _, before := range t.After {
			e, err := end(before)
			if err != nil {
				return 0, err
			}
			start = max(start, e)
		}
		busy[name] = false
		ends[name] = start + t.Hours
		return ends[name], nil
	}
	for name := range tasks {
		if _, err := end(name); err != nil {
			return nil, err
		}
	}
	return ends, nil
}

// finish returns the earliest hour the whole stage can be finished.
func finish(tasks map[string]Task) (int, error) {
	ends, err := earliestEnds(tasks)
	if err != nil {
		return 0, err
	}
	last := 0
	for _, e := range ends {
		last = max(last, e)
	}
	return last, nil
}

// slack returns, for every task, how many hours it can finish later than its earliest
// end without making the whole stage finish later.
func slack(tasks map[string]Task) (map[string]int, error) {
	// TODO: work out the latest end of every task, from the last tasks backwards
	return map[string]int{}, nil
}

// critical returns the tasks with no slack at all, sorted A to Z: any delay to one of
// them delays the whole stage.
func critical(tasks map[string]Task) ([]string, error) {
	// TODO
	return nil, nil
}

func main() {
	tasks := map[string]Task{}
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		if strings.TrimSpace(scanner.Text()) == "" {
			continue
		}
		t, err := parseTask(scanner.Text())
		if err != nil {
			fmt.Println(err)
			return
		}
		tasks[t.Name] = t
	}
	hours, err := finish(tasks)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("part 1: the stage can be ready after", hours, "hours")
	names, _ := critical(tasks)
	fmt.Println("part 2: no task here may run late:", strings.Join(names, ", "))
}
Go runtime not loaded yet

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