Hackbright Code Challenges

Spiral

Spiral

Challenge

Harder

Concepts

Data Structures

Download

spiral.zip

Solution

Spiral: Solution


For this challenge, you’ll need to print points in matrix, going in a spiral.

Imagine a square matrix, like this 4 x 4 matrix. It’s composed of points that are x, y points (top-left is 0, 0):

0,0  1,0  2,0  3,0
0,1  1,1  2,1  3,1
0,2  1,2  2,2  3,2
0,3  1,3  2,3  3,3

Starting at the top left, print the x and y coordinates of each point, continuing in a spiral.

For a 2-by-2 matrix, you’d print:

>>> spiral(2)
(0, 0)
(1, 0)
(1, 1)
(0, 1)

For 3-by-3:

>>> spiral(3)
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(1, 2)
(0, 2)
(0, 1)
(1, 1)

And for a 4-by-4, like our example, above:

>>> spiral(4)
(0, 0)
(1, 0)
(2, 0)
(3, 0)
(3, 1)
(3, 2)
(3, 3)
(2, 3)
(1, 3)
(0, 3)
(0, 2)
(0, 1)
(1, 1)
(2, 1)
(2, 2)
(1, 2)

We’ve given you a file, spiral.py, with a stub function, spiral:

def spiral(matrix_size):
    """Spiral coordinates of a matrix of `matrix_size` size."""

Complete this function.

Hint

How to Start

There are a few ways to think about this. Is this a series of dots? Or a series of boxes?

Also: notice any differences between an even-number martrix width and an odd-number width.