spiral matrix [X-validated]
[This article was first published on R – Xi'an's Og, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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
To leave a comment for the author, please follow the link and comment on their blog: R – Xi'an's Og.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.