Problem Solving with Go course

GridsRotating a Grid

Problem Solving with Go

Display

Theme

Grids · Output exercise

Rotating a Grid

Puzzles sometimes ask you to look at a grid from another side: tilt it north and then west, read columns as rows, or match pieces of a map that have been turned. Instead of writing four versions of your code for four directions, rotate the grid and reuse the same code.

A quarter turn clockwise

Picture a grid with R rows and C columns. After a quarter turn clockwise:

  • the result has C rows and R columns;
  • the leftmost column, read from the bottom up, becomes the top row.
before     turned
abc        da
def        eb
           fc

As a formula: the cell at row r, column c of the result comes from grid[R-1-c][r].

out := make([]string, cols)
for r := 0; r < cols; r++ {
	row := make([]byte, rows)
	for c := 0; c < rows; c++ {
		row[c] = grid[rows-1-c][r]
	}
	out[r] = string(row)
}

Check with a small example

Grid index formulas are easy to mix up. Before using one on real input, try it on a 2×3 grid like the one above and compare the result in your head. Two turns should equal flipping the grid top to bottom and left to right, and four turns should bring back the original. That's a quick way to test your own function.

Variations you'll use:

OperationCell [r][c] of the result comes from
Turn clockwisegrid[R-1-c][r]
Turn counter-clockwisegrid[c][C-1-r]
Transpose (rows become columns)grid[c][r]

Task

Someone photographed a sign with their phone held sideways. This lesson's input is that photo: the sign is turned a quarter turn counter-clockwise.

Turn the grid a quarter turn clockwise, then print the result, one grid row per line. The output must match the expected output exactly. Get it right and you'll be able to read the sign.

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
	}
	grid := strings.Split(strings.TrimSpace(string(data)), "\n")

	// TODO: turn the grid a quarter turn clockwise and print it, one row per line
	for _, row := range grid {
		fmt.Println(row)
	}
}
Go runtime not loaded yet

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