Starburst in R

January 22, 2012
By

(This article was first published on Quantitative Doodles, and kindly contributed to R-bloggers)

> 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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



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.

Sponsors

Mango solutions



plotly webpage

dominolab webpage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training

datasociety

http://www.eoda.de





ODSC

ODSC

CRC R books series





Six Sigma Online Training









Contact us if you wish to help support R-bloggers, and place your banner here.

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)