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)


nomainwin
 
UpperLeftX   = 50
UpperLeftY   = 50
WindowWidth  =900
WindowHeight =930
 
statictext #w.st, "", 10, 850, 870, 40
 
open "Spiral matrix" for graphics_nsb_nf as #w
 
#w "trapclose [quit]"
#w "backcolor darkblue; color cyan; fill darkblue"
 
for N =2 to 50
 
    #w.st "!font courier_new "; int(  60 /N); " bold"
    #w    "down; font arial ";  int( 240 /N); " bold"
 
    g$ ="ruld"                                  '   direction sequence
    if N/2 =int( N/2) then pg =2 else pg =0     '   pointer to current direction
                                                '   last move is left or right depending on N even/odd
    d$ =""
 
    for i =1 to N -1                            '   calculate direction to move
        d$ =nChar$( i, mid$( g$, pg +1, 1)) +d$
        pg =( pg +1) mod 4
        d$ =nChar$( i, mid$( g$, pg +1, 1)) +d$
        pg =( pg +1) mod 4
    next i
 
    d$ =nChar$( N -1, "r") +d$                  '   first row
 
    #w.st "   N ="; N; "  "; d$
 
    xp =60 +250 /N
    yp =80 +250 /N
 
    stp =int( 750 /N)
 
    for i =0 to N^2 -1
        dir$ =mid$( d$, i, 1)
        select case dir$
            case "r"
                xp =xp +stp
            case "d"
                yp =yp +stp
            case "l"
                xp =xp -stp
            case "u"
                yp =yp -stp
        end select
 
        #w "place "; xp; " "; yp
        #w "\"; i
    next i
 
    timer 3000, [on]
    wait
  [on]
    timer 0
    #w "cls"
    scan
next N
 
wait
 
function nChar$( n, i$)
    for i =1 to n
        nChar$ =nChar$ +i$
    next i
end function
 
[quit]
close #w
end