Blog of Andrés Aravena
CMB2:

# Comment on Homework 5

26 March 2019

Did you finish Homework 5? This article shows how someone may draw Trees and Branches using Turtle Graphics and recursive functions in R.

# Trees and branches

Trees are a common recursive structure found in nature. Each branch is like a small tree. More precisely, a tree with n levels has branches with n-1 levels. Your task is to make a function to draw trees with three branches.

The question says that it is recursive. So we will have a function calling itself, and an exit condition.

• One three -> three branches.
• Each branch is a tree

The function should be named tree() with three inputs: the number of levels n, the length of the trunk length, and the angle between the branches angle.

So the idea is something like this:

tree <- function(n, length, angle) {
trunk
branch
branch
branch
}

Each branch is a tree with n-1 levels and with length equal to 0.8 times the length of the previous level. The first branch of every tree is angle degrees to the left of the trunk; the second is aligned with the trunk, and the last one is angle degrees to the right of the trunk.

Now we know how to draw each branch:

tree <- function(n, length, angle) {
turtle_forward(length)
turtle_left(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
}

The most important issue is that the tree() functions must leave the turtle in the same position and the same angle as before. Your function can move the turtle as you wish, but it must leave the turtle as it was at the beginning of the function. The functions turtle_getpos(), turtle_getangle(), turtle_setpos(), and turtle_setangle() can be useful for this.

What is the exit condition?

We add turtle_getpos(), turtle_getangle(), turtle_setpos(), and turtle_setangle() as indicated:

tree <- function(n, length, angle) {
old_pos <- turtle_getpos()
old_angle <- turtle_getangle()
turtle_forward(length)
turtle_left(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
turtle_right(angle)
tree(n-1, length*0.8, angle)
turtle_setangle(old_angle)
turtle_setpos(old_pos[1], old_pos[2])
}

But there is something missing: an exit condition.