I want to draw a diamond shape with R.

Asked 2 years ago, Updated 2 years ago, 40 views

I'd like to draw a diamond with no space on the left as shown in the figure below, but what kind of code can I use to write it?

I want to draw a diamond shape with R.

diamond<-function(max){

    # Upper triangle
    space<-max-1
    for(i in 0:(max-1)}
        for(jin0:space)cat("")
        for(jin0:i)cat("*")
        cat("\n")
        space<-space-1
    }

    # Lower triangle
    space = 1;
    for (i in (max-1): 1) {
        for(jin0:space)cat("")
        for(jin0:(i-1) cat("*")
        cat("\n")
        space<-space+1
    }

r

2022-09-30 19:28

1 Answers

If you want to print a diamond like the one in the image, how about this one?

diamond<-function(n){
  levels<-c(1:n, (n-1):1)
  for (i in levels) {
    cat(strrep(", n-i), strrep("*", 2*i-1", "\n", sep="")
  }
}

diamond (7)


2022-09-30 19:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.