Task

Produce a spiral array.



A   spiral array   is a square arrangement of the first    N2   natural numbers,   where the

numbers increase sequentially as you go around the edges of the array spiraling inwards.



For example, given   5,   produce this array:

 0  1  2  3  4
15 16 17 18  5
14 23 24 19  6
13 22 21 20  7
12 11 10  9  8



Related tasks

   Zig-zag matrix 
   Identity_matrix
   Ulam_spiral_(for_primes)


procedure main(A)        # spiral matrix
N := 0 < integer(\A[1]|5)           # N=1... (dfeault 5)
WriteMatrix(SpiralMatrix(N))
end
 
procedure WriteMatrix(M)             #: write the matrix
every x := M[r := 1 to *M, c := 1 to *M[r]] do
   writes(right(\x|"-", 3), if c = *M[r] then "\n" else "")
return
end
 
procedure SpiralMatrix(N)            #: create spiral matrix
every (!(M := list(N))):= list(N)    # build empty matrix NxN
                                     # setup before starting first turn
corner := 0                          # . corner we're at       
i := -1                              # . cell contents  
r:= 1 ; c :=0                        # . row & col 
cincr := integer(sin(0))             # . column incr
 
until i > N^2 do {
   rincr := cincr                              # row incr follows col                                  
   cincr := integer(sin(&pi/2*(corner+:=1)))   # col incr at each corner
   if (run := N-corner/2)  = 0 then break      # shorten run to 0 at U/R & L/L 
   every run to 1 by -1 do                     
      M[r +:= rincr,c +:= cincr] := i +:= 1    # move, count, and fill
   }
return M
end