ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Mar 04 2021
·
0 comments

Instructions

Test suite

Solution

Given the size, return a square matrix of numbers in spiral order.

The matrix should be filled with natural numbers, starting from 1 in the top-left corner, increasing in an inward, clockwise spiral order, like these examples:

```
1 2 3
8 9 4
7 6 5
```

```
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
```

Reddit r/dailyprogrammer challenge #320 [Easy] Spiral Ascension. https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/

This exercise has been tested on Julia versions >=1.0.

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
using Test
include("spiral-matrix.jl")
@testset "Different valid values" begin
@testset "Empty spiral" begin
@test spiral_matrix(0) == Matrix{Int}(undef,0,0)
end
@testset "Trivial spiral" begin
@test spiral_matrix(1) == reshape([1],(1,1))
end
@testset "Spiral of size 2" begin
@test spiral_matrix(2) == [1 2; 4 3]
end
@testset "Spiral of size 3" begin
@test spiral_matrix(3) == [1 2 3; 8 9 4; 7 6 5]
end
@testset "Spiral of size 4" begin
@test spiral_matrix(4) == [1 2 3 4; 12 13 14 5; 11 16 15 6; 10 9 8 7]
end
@testset "Spiral of size 5" begin
@test spiral_matrix(5) == [1 2 3 4 5; 16 17 18 19 6; 15 24 25 20 7; 14 23 22 21 8; 13 12 11 10 9]
end
end
```

```
function spiral_matrix(n)
if n > 0
# initialize 2D array
a = zeros(Int, n, n)
# countdown array values from highest to lowest
counter = n^2 + 1
# initial spiral diameter
spiral = n % 2
# for odd n, initialize with unique inner spiral of 1 x 1
if spiral == 1
a[div(n+1, 2), div(n+1, 2)] = counter - 1
counter -= 1
end
# step through outer spirals from innermost to outermost
spiral += 2
while spiral <= n
start = floor(Int, (n - spiral)/2) + 1
length = spiral - 1
for i = 1 : length
# update left side of this spiral
a[start + i, start] = counter - i
# update bottom side of this spiral
a[start + length, start + i] = counter - length - i
# update right side of this spiral
a[start + length - i, start + length] = counter - 2 * length- i
# update top side of this spiral
a[start, start + length - i] = counter - 3 * length - i
end
counter -= 4 * length
spiral += 2
end
a
else
Matrix{Int}(undef,0,0)
end
end
```

A huge amount can be learned from reading other peopleâ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments