Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Christmas Tree

Tags:

r

tree

For an assignment, we need to draw a Christmas tree in R. I've searched the internet and found some helpful pieces of advice, but at the end of the day, I don't know how to proceed and hope someone can help me.

This is my code so far.

#ctree: prints a Christmas tree on screen with size N
ctree <- function(N){
for (i in 1:N){
    width = sample("*",i,replace=T)
    cat(width,sep="-","\n")
    }   
cat(width[1],"\n")
}

This leaves me with the middle and right side of my tree (with N=4), which is great, but not enough.

*-
*-*-
*-*-*-
*-*-*-*-
*

I planned on reversing what I had (basically right-aligning the product of the function) to create the left side, subsequently delete the rightmost column of the left side and glue it together with the right side of the tree, creating a Christmas tree.

I really hope that someone can help me achieve this! Looking forward to your advice.

Thanks in advance.

like image 596
Nastasia Griffioen Avatar asked Sep 17 '14 14:09

Nastasia Griffioen


1 Answers

For anyone interested: this is what I ended up doing in R to create a Christmas tree.

#ctree: prints a Christmas tree on screen with amount of branch levels N
ctree <- function(N){
filler = "*"
blank = ""

for (i in 1:N){
    row = c(sample(blank,N-i,replace=T),sample(filler,i,replace=T),sample(blank,N-i,replace=T))
    cat(row,"\n")
    }   
cat(c(sample(blank,(N-1),replace=T),sample(filler,1,replace=T),sample(blank,(N-1),replace=T)),"\n")
} #ctree

This being the result! My own happy little (or big, whatever floats your boat) tree.

enter image description here

like image 136
Nastasia Griffioen Avatar answered Oct 07 '22 10:10

Nastasia Griffioen