Course outline
Course / The terminal and the language

Draw a checkerboard

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/11-07-checkerboard-pattern
cd 11-07-checkerboard-pattern
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Fill in Checkerboard so it returns a Size x Size grid of # and . characters, one row per line, with the top-left cell a #.

Example

Size = 3
fmt.Print(Checkerboard())
#.#
.#.
#.#

The returned string is "#.#\n.#.\n#.#\n". Every row, including the last, ends with a newline.

  • Size = 1 gives "#\n".
  • Size = 2 gives "#.\n.#\n": the characters alternate inside each row, and each row starts with the opposite of the row above.
  • Size = 0 gives "", and so does any negative Size.

Rules

  • Edit checkerboard.go. The function has a // TODO comment and a return line you will change.
  • Size is a variable outside the function. The tests give it different values, so read Size each time the function runs.
  • Use one loop nested inside another: rows outside, cells inside.
  • Use continue in the inner loop to choose the character for a cell: when the cell is a #, add it and continue; otherwise fall through and add the ..
  • Build the result in a string variable declared before the loops.
  • Do not change the line var Size int or the line func Checkerboard() string {. Do not add imports.

What you'll practice

Nested loops, continue, and building a result with an accumulator.

Run it

gonomicon fetch week-1/11-07-checkerboard-pattern
cd 11-07-checkerboard-pattern
gonomicon test
gonomicon submit

Hints

  1. You need a loop inside a loop: the outer one walks the rows, the inner one walks the cells of one row. Add a newline after each row.
  2. A cell is # when (row+col)%2 == 0 and . otherwise. Keep a string accumulator declared before the loops and add one character per cell.
  3. Inside the inner loop: if (row+col)%2 == 0 { result += "#"; continue }, then result += ".". After the inner loop, result += "\n". Return result at the end.

Something wrong with this lesson? Report a problem