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
Crows andRcolumns; - 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:
| Operation | Cell [r][c] of the result comes from |
|---|---|
| Turn clockwise | grid[R-1-c][r] |
| Turn counter-clockwise | grid[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.