Programming Praxis – Unwrapping A Spiral

In today’s Programming Praxis exercise our task is to write a function that walks a 2-dimensional array in a spiral pattern and returns the elements it finds. The provided Scheme solution accomplishes this in 8 lines. Let’s see if we can do any better.

First, a quick import:

import Data.List

The Scheme solution works by having an x and y coordinate and changing them as appropriate. We’re going to take a different approach based on recursion. The easiest way to get the spiral is to remove the first row, rotate the array counterclockwise, and repeat. Rotating the array in this manner can be done by reversing all the rows and then transposing the array.

2 Responses to “Programming Praxis – Unwrapping A Spiral”

Shorter program, yes. But a different data type, lists of lists rather than two-dimensional matrix. And there’s lots of motion. Moving that data all around is expensive if the matrix is large, and may interfere if the matrix is used for some other purpose.

Yeah, this is obviously by no means a highly efficient program. But on this blog, given a choice between length and efficiency I will choose the former, particularly on problems such as this one where practical applications are very limited.