Problem Solving with Go course

Reading InputInput in Blocks

Problem Solving with Go

Display

Theme

Reading Input · Output exercise

Input in Blocks

Many puzzle inputs aren't just lines but blocks: a few lines grouped together, separated by a blank line. Recipe cards, for example:

Pancakes
flour
milk
egg

Lemonade
lemon
water

The simplest trick: a blank line between two blocks means two \n in a row. So split into blocks first, then split each block into lines:

for _, block := range strings.Split(input, "\n\n") {
	lines := strings.Split(block, "\n")
	title := lines[0]  // the first line
	rest := lines[1:]  // everything after it
	fmt.Println(title, len(rest))
}

Two traps

\r\n line endings. Files made on Windows end their lines with \r\n. The blank line becomes \r\n\r\n, so Split(input, "\n\n") finds nothing. Replace them first: strings.ReplaceAll(input, "\r\n", "\n").

Blank lines at the end of the file. If the input ends with "\n" (or several), the last block carries an extra empty line. strings.TrimSpace(input) removes spaces and blank lines at both ends of the input at once.

The starter code already does both steps. Make it a habit in every puzzle.

Task

This lesson's input holds recipe cards. The first line of each card is the recipe's name, and every line after it is one ingredient. Print one line per card, in input order:

<recipe name>: <number of ingredients> ingredients

Then print one last line:

largest: <recipe with the most ingredients>

If several recipes share the largest number of ingredients, pick the one that comes first. The output must match the expected output exactly.

main.go
package main

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

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	input := strings.ReplaceAll(string(data), "\r\n", "\n")
	input = strings.TrimSpace(input)

	// TODO: split the input into cards (blocks separated by a blank line).
	// For each card print "<title>: <n> ingredients",
	// then print "largest: <title>" for the card with the most ingredients.
	_ = input
	fmt.Println("largest: ?")
}
Go runtime not loaded yet

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