Print NxN spiral of ascending numbers

Python

n=input()

matrix=[[j+1]*n for j in range(n)]

x=y=0
for i in range(n)[::-2]:
    x+=i*4;y+=1

    for j in range(i):
        matrix[j+y-1][y]=x+j

    matrix[y-1][y:y+i]=range(x,x-i,-1)

    R=matrix[n-y][y-1]+1
    matrix[n-y][y:n-y+1]=range(R,R+i)

    for j in range(y,y+i-1):
        matrix[j][n-y]=matrix[j-1][n-y]-1

for row in matrix:
    print ' '.join(`r`.zfill(len(`n*n`)) for r in row)
  • An approach that precalculate corner numbers. Eg, for 9x box, 32 56 72 80, which is (n-1)*4 where n is box sizes (9,7,5,3) in this case.
  • Right side of those numbers are 1-, and top to bottom is 1+, so basically generate from left to right, top to bottom, bottom to right, right to top side.

enter image description here

$ echo 9 | python codegolf-769-me.py
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17

Other tests

$ echo 2 | python codegolf-769-me.py
1 4
2 3

$ echo 5 | python codegolf-769-me.py
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

$ echo 10 | python codegolf-769-me.py
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019

In Ruby:

N=gets.to_i

index = -N
width = N
result = []
n = 0
dir=-1

while n < N*N
        dir = (dir + 1) % 4
        dir_x, dir_y = [[0,1],[1,0],[0,-1],[-1,0]][dir]
        width -= 1 if [1,3].include?(dir)

        1.upto(width) { |m|
                n += 1
                index += dir_y * N + dir_x
                result[index] = n
        }
end

width = (N*N).to_s.size
result.each_slice(N) { |l|
        print l.map {|n| "%0#{width}d" % n }.join(" "), "\n"
}

Test:

$ ruby1.9 769.rb <<< 9
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17

An other solution using calculations from here :

N=gets.to_i
r=[]

tr=->x,y{ x+(N-1)/2 + (y+(N-1)/2+(N-1)%2)*N }

r[tr[0,0]] = N*N

1.upto(N*N-1) { |n|
        shell = ((Math.sqrt(n)+1)/2).to_i
        leg = (n-(2*shell-1)**2)/(2*shell)
        element = (n-(2*shell-1)**2)-2*shell*leg-shell+1
        x,y = [[element,-shell],[shell,element],[-element,shell],[-shell,-element]][leg]
        r[tr[x,y]] = N*N-n
}

r.each_slice(N) {|l|
        puts l.map { |n|
                "%0#{(N*N).to_s.size}d" % (n or 0)
        }.join(" ")
}

Test:

$ ruby1.9 769-2.rb <<< 5
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

In Python3:

n=int(input())
results = {}
val = 1
location = (0,0)
direction = (0,1)

def nxt():
    return (location[0]+direction[0], location[1]+direction[1])

while val<=n*n:
    if set([-1,n]).intersection(nxt()) or nxt() in results:
        direction = (direction[1],direction[0]*-1)

    results[location], location, val = str(val), nxt(), val+1

slen = len(str(n*n))
for y in range(n):
    print( *[results[(x,y)].rjust(slen,'0') for x in range(n)] )

Sample Output for 7:

01 24 23 22 21 20 19
02 25 40 39 38 37 18
03 26 41 48 47 36 17
04 27 42 49 46 35 16
05 28 43 44 45 34 15
06 29 30 31 32 33 14
07 08 09 10 11 12 13

edit: A recursive solution - 263 Bytes

def a(m,s):
 b,r,t=m-s*s+1,s-1,range
 return[[[]],[[m]]][s]if s<2 else[[b]+list(t(b+4*r-1,b+3*r-1,-1))]+[[b+y+1]+a(m,s-2)[y]+[b+3*r-y-1]for y in t(s-2)]+[list(t(b+r,b+2*r+1))]
n=int(input())
for r in a(n*n,n):
 print(*[str(x).zfill(len(str(n*n)))for x in r])