CS111 PreLab 6

This prelab asks you to practice using and understanding recursion. Please don't spend more than 15-20 minutes on each part.

Part 1 -- JEM Diagrams for Recursive methods

Below are the declarations for two classes: a ThrowerWorld class that is a subclass of BuggleWorld and a ThrowerBuggle class that is a subclass of Buggle.

// a BuggleWorld in which Buggles throw Bagels
public class ThrowerWorld extends BuggleWorld {
  public void run () {
    ThrowerBuggle tara = new ThrowerBuggle();
    tara.throwBagel(3);
  }
}
 
class ThrowerBuggle extends Buggle {
  public void throwBagel (int distance) {
    if (distance == 0) {
      dropBagel();
    } else {
      forward();
      throwBagel(distance - 1);
      backward();
    }
  }
}
 

Task 1a) Draw the result (in a ThrowerWorld grid) of asking tara to throw bagels at distances of 0, 1, 2, 3, 4, and 5. Use a different grid for each distance. The size of the grid doesn't matter (just make it large enough so the buggle doesn't run into walls). When given recursive code, it is usually a good idea to draw on paper a couple of instances of running the code beginning with the easiest case and working up.

Task 1b) Draw a Java Execution Model diagram that shows all of the execution frames created by invoking the run() method on an instance of the ThrowerWorld class. Your diagram should depict the point in time when the invocation of run() returns. Although Java can discard an execution frame when control returns from it, you should not discard any frames when drawing your diagram.

Part 2 -- Recursion Practice in BuggleWorld

Below is the skeleton of the triangle method of the TriangleBuggle class which extends Buggle:

public void triangle(int size) {
  // add your code here
}
 

Your task is to define the triangle method using a recursive strategy. The output from creating a TriangleBuggle tria and starting her at point (5,2) and headed in the direction North before asking her to draw triangles of different sizes is shown below.


tria.triangle(0);


tria.triangle(1);


tria.triangle(2);


tria.triangle(3);


tria.triangle(4);


tria.triangle(5);

When writing the triangle method, you can assume that the TriangleBuggle has plenty of space to move around (ie don't worry about bumping into walls).