spiral matrix [X-validated]

One recent code-golf challenge was to write the shortest possible code representing the first n² integers in a spiral progression, e.g.,

 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 

While I did not come close to the best R code (with 67 bytes), this proved an interesting coding exercise, looking for a way to rotate a matrix in R, and then filling one batch at a time. Here is my clumsy if original (?) R output exploiting the vector representation of matrices in R:

r=function(x)apply(t(x),2,rev) #-90⁰ rotation
w=which;m=min
X=diag(0,n)
X[1:n]=n:1
while(!m(X)){
  X=r(X)
  i=m(w(!X))
  j=w(!!X)
  j=m(j[j>i])-1
  X[i:j]=-m(-X)+(j-i+1):1}
while(X[1]>1)X=r(X)

although I later found a webpage proposing (non-optimised) solutions in most computer languages. Thanks to Robin’s remarks, a tighter version is

r=function(n){
w=which
X=diag(0,n)
X[n,]=m=n:1
while(!min(X)){
i=w(!X)[1]
j=w(!!X[-1:-i])
X[i-1+1:j]=max(X)+j:1       #produces warnings
X=t(X)[m,]}                     #-90⁰ rotation
`if`(n%%2,t(t(X)[m,])[m,],X)-1} #180⁰ rotation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: