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

# ruud's solution

## to Spiral Matrix in the Julia Track

Published at Mar 18 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:

###### Spiral matrix of size 3
``````1 2 3
8 9 4
7 6 5
``````
###### Spiral matrix of size 4
`````` 1  2  3 4
12 13 14 5
11 16 15 6
10  9  8 7
``````

## Source

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

## Version compatibility

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

## Submitting Incomplete Solutions

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

### runtests.jl

``````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::Int,
spiral= nothing,
cur_n= nothing,
count= 1
)
# we use recursion: create the matrix
spiral==nothing && return spiral_matrix(n, Matrix{Int64}(zeros(n,n)),n,count)
n==0 && return spiral

# calculate the run for a single side
# n: the size of the spiral
# cur_n: the size of the current turn of the spiral
offset= (n-cur_n)Ã·2
from= 1+offset
to=  n-offset-1

# for uneven n we end with a turn of a single cell
if cur_n == 1
spiral[from,from]= count;
return spiral
end

# the first side of the turn: left to right
for xx= from:to
spiral[from,xx]= count; count+=1
end

# second side: top bottom on the right
for yy= from:to
spiral[yy,to+1]= count; count+= 1
end

# third side: right to left on the bottom
for xx= range(to+1,from+1,step= -1)
spiral[to+1,xx]= count; count+= 1
end

# fourth side: bottom to top on the left
for yy= range(to+1,from+1,step= -1)
spiral[yy,from]= count; count+= 1
end

# after a complete turn rerun the function for a turn that is 2 smaller than cur_n
cur_n > 0 && spiral_matrix(n,spiral, cur_n-2, count)

# return the spiral
spiral
end``````