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)


/* NetRexx */
options replace format comments java crossref symbols binary
 
parse arg size .
 
if \size.datatype('W') then do
  printArray(generateArray(3))
  say
  printArray(generateArray(4))
  say
  printArray(generateArray(5))
  say
  end
else do
  printArray(generateArray(size))
  say
  end
 
return
 
-- -----------------------------------------------------------------------------
method generateArray(dimension = int) private static returns int[,]
 
  -- the output array
  array = int[dimension, dimension]
 
  -- get the number of squares, including the center one if
  -- the dimension is odd
 
  squares = dimension % 2 + dimension // 2
 
  -- length of a side for the current square
  sidelength = dimension
  current = 0
 
  loop i_ = 0 to squares - 1
 
    -- do each side of the current square
    -- top side
    loop j_ = 0 to sidelength - 1
      array[i_, i_ + j_] = current
      current = current + 1
      end j_
 
    -- down the right side
    loop j_ = 1 to sidelength - 1
      array[i_ + j_, dimension - 1 - i_] = current
      current = current + 1
      end j_
 
    -- across the bottom
    loop j_ = sidelength - 2 to 0 by -1
      array[dimension - 1 - i_, i_ + j_] = current
      current = current + 1
      end j_
 
    -- and up the left side
    loop j_ = sidelength - 2 to 1 by -1
      array[i_ + j_, i_] = current
      current = current + 1
      end j_
 
    -- reduce the length of the side by two rows
    sidelength = sidelength - 2
    end i_
 
  return array
 
-- -----------------------------------------------------------------------------
method printArray(array = int[,]) private static
 
  dimension = array[1].length
  rl = formatSize(array)
  loop i_ = 0 to dimension - 1
    line = Rexx("|")
    loop j_ = 0 to dimension - 1
      line = line Rexx(array[i_, j_]).right(rl)
      end j_
    line = line "|"
    say line
    end i_
 
  return
 
-- -----------------------------------------------------------------------------
method formatSize(array = int[,]) private static returns Rexx
 
  dim = array[1].length
  maxNum = Rexx(dim * dim - 1).length()
 
  return maxNum
 
 