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])
yes according to me. – Wile E. Coyote – 2011-02-09T16:15:54.353
According to my calculations, the length of field is
L = floor(log10(N^2)) + 1
Is this correct? – Hristo Hristov – 2011-02-09T16:17:31.250What's the upper limit on
N
? – None – 2011-02-10T08:26:20.903I am interested in the algorithm and the cleanliness of the implementation. So, let's don't bother with very big numbers and set the upper limit of N to 42 :) – Hristo Hristov – 2011-02-10T09:00:56.530
Was this motivated by the Ulam Spiral? (although your spiral is descending if viewed as starting on the inside)
– smci – 2012-01-21T11:58:46.210@smci no, it was an interesting programming exercise I saw in a book – Hristo Hristov – 2012-01-21T13:58:00.153
Oh. I thought the 42 in the spiral was telltale because of the well-known prime generator formula, which is what Ulam's Spiral is about. – smci – 2012-01-21T21:43:16.860
42 is from The Hitchhiker's Guide to the Galaxy :) – Hristo Hristov – 2012-01-22T09:33:16.063