Starburst in R

January 22, 2012
By

[This article was first published on Quantitative Doodles, 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.

> starburst('Matrices!')
M   M   M
 a  a  a 
  t t t  
   rrr   
Matrices!
   ccc   
  e e e  
 s  s  s 
!   !   !

wrathematic led me FibBuzz, which led me to Starburst. Now that it’s over, you can see my solution, which uses R matrices.

v=strsplit(readLines('stdin'),'')[[1]]
d=length(v)
h=d/2+0.5
m=matrix(' ',d,d)
diag(m)=m[h,]=m[,h]=diag(m[d:1,])=v
invisible(cat((apply(m,2,paste,collapse='')),sep='\n'))

It’s rather long, but I think that’s more the input-reading and the printing rather than the arranging. Here’s the code in a more legible form.

starburst<-function(s){
  letters<-strsplit(s,'')[[1]]
  side<-nchar(s)
  half<-side/2+0.5
  m<-matrix(' ',side,side)
  diag(m)<-m[half,]<-m[,half]<-diag(m[side:1,])<-letters
  invisible(cat((apply(m,2,paste,collapse='')),sep='\n'))
}
s<-readLines('stdin') # s<-'Tommy' # if you don't want to read from stdin

And then we run it.

> starburst(s)
> starburst('Voilà')                                         
V V V
 ooo 
Voilà
 lll 
à à à

It currently doesn’t work for single-letter words.

> starburst('R')
Error in `diag<-`(`*tmp*`, value = "R") : 
  only matrix diagonals can be replaced

To leave a comment for the author, please follow the link and comment on their blog: Quantitative Doodles.

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.



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers

Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)