Problem Solving with Go course

Capstone PuzzlesBike Rentals, Part 1

Problem Solving with Go

Display

Theme

Capstone Puzzles · Test exercise

Bike Rentals, Part 1

The puzzle

A bike shop by the river keeps a paper log of every rental: the bike, when it went out and when it came back.

B04 09:05-10:30
B11 09:20-09:50
B02 09:40-12:15

Times are on a 24-hour clock. A bike is out from the minute it leaves up to, but not including, the minute it comes back: a bike returned at 10:30 can go out again at 10:30, and at that minute it counts once, not twice. The same bike can appear in several rentals.

The owner wants to know whether she has enough bikes. What is the most bikes out at the same moment during the day?

This lesson's input has the log, a blank line, and a list of times the owner will ask about in part 2. Part 1 only needs the log.

Task

  1. Complete clock(s string) (int, error): turn "09:05" into minutes after midnight (545). Hours go from 00 to 23 and minutes from 00 to 59; anything else is an error.
  2. Complete parseRental(line string) (Rental, error): read a line such as B04 09:05-10:30. A line without a bike, without both times, or that ends at or before its start is an error.
  3. Complete peak(rentals []Rental) int: the most bikes out at once.

Checking every minute of the day works for one day, but think about what happens with a year of logs. There's a way that only looks at the moments when something changes.

main.go
package main

import (
	"fmt"
	"io"
	"os"
	"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) {
	// TODO
	return 0, 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) {
	// TODO
	return Rental{}, nil
}

// peak returns the most bikes out at the same moment.
func peak(rentals []Rental) int {
	// TODO
	return 0
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	log, _, _ := 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")
}
Go runtime not loaded yet

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