简体   繁体   English

在 R 中绘制带 * 的形状

[英]Draw shape with * in R

I am studying R, I was resquested to create the next pattern on R:我正在研究 R,我被要求在 R 上创建下一个模式:

*********
 *** *** 
  *****  
   * *   
    *

(With that space in the middle) (中间那个空格)

I tried this code but the answer is not correct:我试过这段代码,但答案不正确:

pattern <- function(triangle) {
  m = 1;
  for (i in (triangle - 1):1) {
    for (j in 0:m) cat(' ')
    for (j in 0:(i - 1)) cat('*')
    cat('\n')
    m <- m + 1
  }
}
pattern(10)

Could someone please help me?有人可以帮我吗?

Another version using paste() :另一个使用paste()的版本:

pattern <- function(layer){
  for (i in 1:layer){
    n_blank <- paste(rep(" ",i-1),collapse="")
    n_star <- paste(rep("*",layer-i),collapse="")
    if(layer%%2==0){
      central_element <- ifelse(i%%2==0,"*"," ")
    }else{
      central_element <- ifelse(i%%2==1,"*"," ")
    }
    
    cat(paste(n_blank,n_star,central_element,n_star,n_blank,sep=""))
    cat('\n')

  }
}

pattern(5)
*********
 *** *** 
  *****  
   * *   
    *  
pattern(9)
*****************
 ******* ******* 
  *************  
   ***** *****   
    *********    
     *** ***     
      *****      
       * *       
        *    

I'd probably use recursion here and avoid loops altogether:我可能会在这里使用递归并完全避免循环:

pattern <- function(n, max_n = n) {
  if(n %% 2 == 1) {
    cat(rep(" ", max_n - n), rep("*", 2 * n - 1), rep(" ", max_n - n), "\n",
        sep = "")
  } else {
    cat(rep(" ", max_n - n), rep("*", n-1), " ", rep("*", n-1), 
        rep(" ", max_n - n), "\n", sep = "")
  }
  if(n > 1) pattern(n - 1, max_n)
}

Testing, we have:测试,我们有:

pattern(5)
#> *********
#>  *** *** 
#>   *****  
#>    * *   
#>     *

pattern(10)
#> ********* *********
#>  ***************** 
#>   ******* *******  
#>    *************   
#>     ***** *****    
#>      *********     
#>       *** ***      
#>        *****       
#>         * *        
#>          *

Created on 2023-01-12 with reprex v2.0.2创建于 2023-01-12,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM