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.
- 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. - Complete
distance(a, b Point) int: the Manhattan distance between two points. Theabsfunction is already there.