Clear Filters
Clear Filters

I need help using recursion in OOP: : A level 1 tree is a line. A level 2 tree is a line and two level 1 trees (it looks like: Y). A level 3 tree is a line and two level 2 trees. A level 4 tree is a line and two level 3 trees.

1 view (last 30 days)
I have a class set up with functions to drive forward and make turns. I just don't know how to make this work in a loop. The following is what the program should do for a n-level tree. If n is 0, do nothing. Otherwise, drive forward d, turn left a degrees, draw a level n-1 tree, turn right 2a degrees, draw a level n-1 tree, turn left a degrees, and drive backward d
  1 Comment
Kyle Reagan
Kyle Reagan on 14 Oct 2016
t = Turtle(); a = 40; b = 4; while n > 0
t = t.fd(b);
t = t.lt(a);
t = t.fd(b);
t = t.bk(b);
t = t.rt(2*a);
t = t.fd(b);
t = t.bk(b);
t = t.lt(a);
t = t.bk(b);
end
This is what I have so far.

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 14 Oct 2016
Ah, LOGO and turtle graphics. That takes me back ... longer ago than I'd care to admit.
Is the code you posted in a function named tree or something similar? If it is, what input arguments does the function accept? If it is not in a function, you should create a function named tree. For this to be a recursive program, the tree function will have to call itself.
I would put each clause (a section ending in a period or a comma) in your instructions on how to draw the tree on a separate line of your file as a comment. Then after each of those comment lines, write a single command that does what the comment line says to do.
  4 Comments
Kyle Reagan
Kyle Reagan on 17 Oct 2016
Now I have it so that my input is n and my output is y.
obj = Turtle(); function [y] = tree(obj,n) % Creates tree to the order n t = Turtle(); a = 60; % angle in degrees d = 4; % distance turtle travels
% If n is 0, if n <= 0 % do nothing. t = t.fd(0); % Otherwise, else % drive forward d, t = t.fd(d); % turn left a degrees, t = t.lt(a); % draw a level n-1 tree, y = tree(n-1) % turn right 2a degrees, t = t.rt(2*a); % draw a level n-1 tree, y = tree(n-1) % turn left a degrees, t = t.lt(a); % and drive backward d t = t.bk(d); end end
Steven Lord
Steven Lord on 17 Oct 2016
Almost. You've defined tree to have two inputs, obj and n. You're calling it in your recursive step with one input, just n-1. You should call it with two inputs, obj and n-1. Otherwise at the recursion step when you execute "if n <=0" the variable n won't exist and you'll receive an error.

Sign in to comment.

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!