Problem Solving with Go course

Capstone PuzzlesBike Rentals, Part 2

Problem Solving with Go

Display

Theme

Capstone Puzzles · Test exercise

Bike Rentals, Part 2

The owner liked your number so much that she wants more. Throughout the day she jots down times on a sticky note and later asks: how many bikes were out at each of these times?

The puzzle, continued

The list after the blank line in your input holds her times. For each one, count the rentals that are out at that minute, with the same rule as before: a rental from Start to End is out at minute t when Start <= t < End.

09:30 → 2 bikes
10:30 → 4 bikes

One time is easy: loop over the log. But the owner keeps a log for the whole season and asks about thousands of times. Looking at every rental for every time grows like rentals × times. Find a way that answers each question without going through the whole log again.

Task

Your part 1 code is already there. Complete outAt(rentals []Rental, times []int) []int: for every minute in times, in the same order, how many bikes are out at that minute.

main.go
package main

import (
	"fmt"
	"io"
	"os"
	"slices"
	"strconv"
	"strings"
)

// Rental is one bike out from Start until End, in minutes after midnight. The bike is
// back at End: it isn't out at minute End any more.
type Rental struct {
	Bike       string
	Start, End int
}

// clock turns "09:05" into minutes after midnight.
func clock(s string) (int, error) {
	h, m, ok := strings.Cut(s, ":")
	hours, err1 := strconv.Atoi(h)
	minutes, err2 := strconv.Atoi(m)
	if !ok || err1 != nil || err2 != nil || hours < 0 || hours > 23 || minutes < 0 || minutes > 59 {
		return 0, fmt.Errorf("bad time %q", s)
	}
	return hours*60 + minutes, nil
}

// parseRental reads a line such as "B04 09:05-10:30". The end must be after the start.
func parseRental(line string) (Rental, error) {
	bike, span, ok := strings.Cut(strings.TrimSpace(line), " ")
	from, to, ok2 := strings.Cut(span, "-")
	if !ok || !ok2 || bike == "" {
		return Rental{}, fmt.Errorf("bad rental %q", line)
	}
	start, err := clock(from)
	if err != nil {
		return Rental{}, err
	}
	end, err := clock(to)
	if err != nil {
		return Rental{}, err
	}
	if end <= start {
		return Rental{}, fmt.Errorf("rental %q ends before it starts", line)
	}
	return Rental{bike, start, end}, nil
}

// event is a moment when the number of bikes out changes by delta (+1 or -1).
type event struct {
	at, delta int
}

// peak returns the most bikes out at the same moment.
func peak(rentals []Rental) int {
	var events []event
	for _, r := range rentals {
		events = append(events, event{r.Start, +1}, event{r.End, -1})
	}
	// By time; at the same minute, returns (-1) before new rentals (+1).
	slices.SortFunc(events, func(a, b event) int {
		if a.at != b.at {
			return a.at - b.at
		}
		return a.delta - b.delta
	})
	out, most := 0, 0
	for _, e := range events {
		out += e.delta
		most = max(most, out)
	}
	return most
}

// outAt returns, for every minute in times, how many bikes are out at that minute.
func outAt(rentals []Rental, times []int) []int {
	// TODO: the shop asks about thousands of minutes; avoid looking at every
	// rental for every minute
	return make([]int, len(times))
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	log, asked, _ := strings.Cut(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n\n")
	var rentals []Rental
	for _, line := range strings.Split(strings.TrimSpace(log), "\n") {
		r, err := parseRental(line)
		if err != nil {
			fmt.Println(err)
			return
		}
		rentals = append(rentals, r)
	}
	fmt.Println("part 1: at most", peak(rentals), "bikes out at once")

	var times []int
	for _, s := range strings.Fields(asked) {
		t, err := clock(s)
		if err != nil {
			fmt.Println(err)
			return
		}
		times = append(times, t)
	}
	for i, n := range outAt(rentals, times) {
		fmt.Printf("part 2: %d bikes out at %02d:%02d\n", n, times[i]/60, times[i]%60)
	}
}
Go runtime not loaded yet

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