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)


$ include "seed7_05.s7i";
 
const type: matrix is array array integer;
 
const func matrix: spiral (in integer: n) is func
  result
    var matrix: myArray is matrix.value;
  local
    var integer: i is 0;
    var integer: dx is 1;
    var integer: dy is 0;
    var integer: x is 1;
    var integer: y is 1;
    var integer: nx is 0;
    var integer: ny is 0;
    var integer: swap is 0;
  begin
    myArray := n times n times 0;
    for i range 1 to n**2 do
      myArray[x][y] := i;
      nx := x + dx;
      ny := y + dy;
      if nx >= 1 and nx <= n and ny >= 1 and ny <= n and myArray[nx][ny] = 0 then
        x := nx;
        y := ny;
      else
        swap := dx;
        dx := -dy;
        dy := swap;
        x +:= dx;
        y +:= dy;
      end if;
    end for;
  end func;
 
const proc: writeMatrix (in matrix: myArray) is func
  local
    var integer: x is 0;
    var integer: y is 0;
  begin
    for key y range myArray do
      for key x range myArray[y] do
        write(myArray[x][y] lpad 4);
      end for;
      writeln;
    end for;
  end func;
 
const proc: main is func
  begin
    writeMatrix(spiral(5));
  end func;