Problem Solving with Go course

GridsPoints as Map Keys

Problem Solving with Go

Display

Theme

Grids · Test exercise

Points as Map Keys

Not every grid comes as text. Sometimes you only get movement commands, and the grid "grows" in every direction, negative coordinates included. A slice can't be indexed with -3. The fix: store only the cells that matter in a map, with the position as the key.

A struct as a key

A map key can be any type that can be compared with ==. A struct whose fields are comparable qualifies:

type Point struct {
	Row, Col int
}

seen := map[Point]bool{}
seen[Point{0, 0}] = true
seen[Point{-3, 4}] = true

fmt.Println(seen[Point{-3, 4}]) // true
fmt.Println(len(seen))          // 2

Two Points with the same values are the same key. Arrays like the [2]int from the previous lesson work too, but a struct with field names reads more easily.

A map like this is a sparse grid: only the cells you've touched are stored, however large the area.

Moving one step at a time

When the command is "go 4", don't jump straight to the end. If the puzzle asks which cells were passed, you have to mark every cell on the way:

step := Point{0, 1} // east
for i := 0; i < 4; i++ {
	at = Point{at.Row + step.Row, at.Col + step.Col}
	seen[at] = true
}

Manhattan distance

On a grid without diagonal moves, the shortest distance between two cells is the row difference plus the column difference: |r1 - r2| + |c1 - c2|. It's called the Manhattan distance, like walking around city blocks. Go has no abs for int, so write your own.

Task

A robot vacuum starts at {0, 0} and takes commands like E 4 (a direction N, S, W or E, then a number of steps). N decreases Row, S increases Row, W decreases Col and E increases Col. The steps map already holds the step for each direction.

  1. Complete walk(commands []string) (cleaned int, end Point, err error): how many different cells the robot passed over (the starting cell counts) and where it ended. Return an error if the direction is unknown, if there's no space, or if the number of steps isn't a non-negative whole number.
  2. Complete distance(a, b Point) int: the Manhattan distance between two points. The abs function is already there.
main.go
package main

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

// Point is a cell: Row grows downwards, Col grows to the right.
type Point struct {
	Row, Col int
}

// One step in each direction.
var steps = map[string]Point{
	"N": {-1, 0},
	"S": {1, 0},
	"W": {0, -1},
	"E": {0, 1},
}

// walk follows commands such as "N 3" from {0, 0}, one cell at a time. It returns
// how many different cells were cleaned (the start included) and where it stopped.
func walk(commands []string) (cleaned int, end Point, err error) {
	// TODO: keep a map[Point]bool of the cells visited, starting with {0, 0}
	return 0, Point{}, nil
}

// distance is the Manhattan distance: steps along rows plus steps along columns.
func distance(a, b Point) int {
	// TODO
	return 0
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	commands := strings.Split(strings.TrimSpace(string(data)), "\n")
	cleaned, end, err := walk(commands)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("cells cleaned:", cleaned)
	fmt.Println("stopped at:", end, "distance from the dock:", distance(Point{}, end))
}
Go runtime not loaded yet

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