I am studying R, I was resquested to create the next pattern on 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?
CodePudding user response:
Another version using 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)
*****************
******* *******
*************
***** *****
*********
*** ***
*****
* *
*
CodePudding user response:
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