Problem Solving with Go course

GridsA Grid from the Input

Problem Solving with Go

Display

Theme

Grids · Test exercise

A Grid from the Input

Maps, mazes, game boards, orchards: lots of puzzles hand you a grid of characters as input.

..#.......
.....##...
..S....#..

Every line is a row of the grid, and every character is a cell. The simplest way to store it is a slice of rows: []string or [][]byte.

Rows and columns

Pick one order and stick to it: row first, then column. grid[r][c] is the cell in row r (from the top, starting at 0) and column c (from the left, starting at 0).

rows := len(grid)
cols := len(grid[0])
cell := grid[2][2] // 'S'

Many grid bugs come from mixing up (x, y) and (row, column). When a puzzle talks about x and y, remember that x is the column and y is the row.

[]string or [][]byte?

Reading a cell is the same in both: grid[r][c] gives you one byte. The difference is that strings can't be changed. If you need to change cells (marking a path, simulating changes), use [][]byte:

row := []byte("..S..")
row[2] = '.'

Compare cells with a character literal in single quotes: grid[r][c] == '#'. For ASCII input, one character is one byte.

Check the shape

Puzzle grids are almost always rectangles. If a row is shorter, something usually went wrong while reading the input: spaces at the end of a line, a \r from Windows, or a blank line at the end of the file. Checking the widths up front saves a lot of bug hunting.

Task

This lesson's input is a harbour map: . is water, # is a rock, S is the ship and H is the dock.

  1. Complete parseGrid(input string) ([][]byte, error). Replace \r\n with \n, drop spaces and blank lines at both ends with strings.TrimSpace, then split into lines. Return an error if the input is empty or if any row's width differs from the first row's.
  2. Complete find(grid [][]byte, ch byte) (row, col int, ok bool): the position of the first ch, reading left to right and top to bottom.
  3. Complete count(grid [][]byte, ch byte) int: the number of cells holding ch.
main.go
package main

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

// parseGrid turns the input into rows of bytes. Every row must be as wide as the first.
func parseGrid(input string) ([][]byte, error) {
	// TODO: normalise line endings, trim, split into lines, check the widths
	return nil, nil
}

// find returns the row and column of the first ch, reading left to right, top to bottom.
func find(grid [][]byte, ch byte) (row, col int, ok bool) {
	// TODO
	return 0, 0, false
}

// count returns how many cells hold ch.
func count(grid [][]byte, ch byte) int {
	// TODO
	return 0
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	grid, err := parseGrid(string(data))
	if err != nil {
		fmt.Println("bad map:", err)
		return
	}
	fmt.Println("size:", len(grid), "rows")
	if r, c, ok := find(grid, 'S'); ok {
		fmt.Printf("ship at row %d, column %d\n", r, c)
	}
	fmt.Println("rocks:", count(grid, '#'))
}
Go runtime not loaded yet

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