Problem Solving with Go course

Reading InputFixed Formats: regexp and fmt.Sscanf

Problem Solving with Go

Display

Theme

Reading Input · Test exercise

Fixed Formats: regexp and fmt.Sscanf

Sometimes a line has a fixed sentence shape, with a few values that change inside it:

KRL 07:15 Bogor -> Jakarta Kota (54 min)

Fields would split Jakarta Kota into two parts. For shapes like this a regular expression fits better: you write the pattern once, then pick out the captured parts.

regexp with capture groups

var tripLine = regexp.MustCompile(`^(\S+) (\d\d:\d\d) (.+) -> (.+) \((\d+) min\)$`)

m := tripLine.FindStringSubmatch(line)
if m == nil {
	// the line doesn't match the pattern
}
// m[0] = the whole line, m[1] = "KRL", m[2] = "07:15", m[3] = "Bogor", ...

The pattern pieces you'll use most:

PatternMeaning
\done digit
\d+one or more digits
\S+one or more characters that aren't spaces
.+one or more characters of any kind
( )a capture group: this part goes into m[1], m[2], ...
\(a real parenthesis, not a group
^ and $start and end of the line

Write patterns in backticks (`) so \d doesn't have to be written \\d. Build the regexp once at package level with MustCompile, not inside a loop.

fmt.Sscanf for small pieces

For very simple shapes, fmt.Sscanf reads values straight into variables:

var hour, minute int
_, err := fmt.Sscanf("07:15", "%d:%d", &hour, &minute) // hour = 7, minute = 15

Sscanf suits short pieces such as a time or a coordinate like 3,4. For a whole long line, a regexp is usually easier to read and tells you clearly when the line doesn't match.

Keep times as minutes

Doing arithmetic with "07:15" is awkward. Turn it into one number, such as minutes after midnight (7*60 + 15 = 435), compute with that, then format it back at the end with fmt.Sprintf("%02d:%02d", h, m). The % operator wraps the time past midnight: (1420 + 545) % 1440 = 525, which is 08:45.

Task

A train timetable is written as <train> <HH:MM> <from> -> <to> (<duration> min). Station names can be more than one word.

  1. Complete parseTrip(line string) (Trip, error) with tripLine.FindStringSubmatch. Turn the departure time into minutes after midnight (fmt.Sscanf with "%d:%d"), and the duration with strconv.Atoi. Return an error if the line doesn't match the pattern, or if the hour is above 23 or the minute above 59.
  2. Complete arrival(t Trip) string: the arrival time as HH:MM, wrapping past midnight.
main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
)

type Trip struct {
	Train   string
	Depart  int // minutes after midnight
	From    string
	To      string
	Minutes int
}

// tripLine matches lines like "KRL 07:15 Bogor -> Jakarta Kota (54 min)".
var tripLine = regexp.MustCompile(`^(\S+) (\d\d:\d\d) (.+) -> (.+) \((\d+) min\)$`)

// parseTrip turns one timetable line into a Trip.
func parseTrip(line string) (Trip, error) {
	// TODO: use tripLine.FindStringSubmatch, fmt.Sscanf for the time, strconv.Atoi for the minutes
	return Trip{}, nil
}

// arrival returns the arrival time as "HH:MM", wrapping past midnight.
func arrival(t Trip) string {
	// TODO
	return ""
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		trip, err := parseTrip(scanner.Text())
		if err != nil {
			fmt.Println("bad line:", err)
			continue
		}
		fmt.Printf("%s %s -> %s arrives %s\n", trip.Train, trip.From, trip.To, arrival(trip))
	}
}
Go runtime not loaded yet

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