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") }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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: