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)


DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
 
INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)
 
PROC PrintMatrix(BYTE ARRAY a BYTE size)
  BYTE i,j,v
 
  FOR j=0 TO size-1
  DO
    FOR i=0 TO size-1
    DO
      v=a(Index(size,i,j))
      IF v<10 THEN
        Print("  ")
      ELSE
        Print(" ")
      FI
      PrintB(v)
    OD
    PutE()
  OD
RETURN
 
PROC FillMatrix(BYTE ARRAY a BYTE size)
  INT lev,maxLev,dist,maxDist,v
 
  maxLev=size/2
  IF (size&1)=0 THEN
    maxLev==-1
  FI
  maxDist=size-1
  v=1
  FOR lev=0 TO maxLev
  DO
    FOR dist=0 TO maxDist
    DO
      a(Index(size,lev+dist,lev))=v v==+1
    OD
    FOR dist=0 TO maxDist-1
    DO
      a(Index(size,size-1-lev,lev+dist+1))=v v==+1
    OD
    FOR dist=0 TO maxDist-1
    DO
      a(Index(size,size-2-lev-dist,size-1-lev))=v v==+1
    OD
    FOR dist=0 TO maxDist-2
    DO
      a(Index(size,lev,size-2-lev-dist))=v v==+1
    OD
    maxDist==-2
  OD
RETURN
 
PROC Test(BYTE size)
  BYTE ARRAY mat(MAX_MATRIX_SIZE)
 
  PrintF("Matrix size: %B%E",size)
  FillMatrix(mat,size)
  PrintMatrix(mat,size)
  PutE()
RETURN
 
PROC Main()
  Test(5)
  Test(6)
RETURN