DEV Community

Discussion on: Daily Challenge #2 - String Diamond

Collapse
 
mdarrik profile image
Darrik Moberg • Edited

This took me longer than it should have. But I haven't worked with R in almost 2 years. Sure you could do it more efficiently with just a loop, but I learned some stuff about concatenating matrices to strings in R this way so I call it a win.

R:

diamond <- function(n) {
  if(!n %% 2 || n<=0) { return(NA)}
  else if(n==1) { return("*")}
  matrix(1:n, nrow=(n*2 - 1), ncol=n, byrow = TRUE)
  numStarsPerRow <- matrix(c(seq(from = 1, to= n, by=2),
                             seq(from=n-2, to = 1, by = -2)),
                           nrow=n, ncol=n)
  startcol <- matrix(c(seq(from =(n+1)/2, to = 1, by = -1),
                       seq(from = 2, to = (n+1)/2, by = 1)),
                     nrow=n,ncol=n)
  colNum <- matrix(1:n, ncol=n, nrow=n,
                   byrow = TRUE)
starBools <- (colNum >= startcol & colNum <= (startcol + numStarsPerRow) -1)
paste(apply(ifelse(starBools,"*"," "),2,paste, collapse=""),collapse ="\n")
}