CS111, Wellesley College, 2006

Lab 8

Wedn/Thur, October 25/26, 2006

Recurses, Executed Again!

Total checkmarks:

Today:


Unfurling a recursive function


public int boo (int n) {
    if (n<=2) {
      return n;
    } else {
      return n + boo(n/2) + boo(n/3);
    }
}

Given the function boo above, what is

Note that integer division in Java yields integers, so, for example [10/3 is 3 (not 3.33) and 5/3 is 1 (not 1.66)].

Other functions for practice:

public int sumUpTo (int n) {
    if (n < 1) {
      return 0;
    } else {
      return n + sumUpTo(n-1);
}


public int pow (double x, int n) {
    if (n > 1) {
      return x*pow(x,n-1);
    } else if (n<0) {
         return 1.0/pow(x,-n);
    } else if (n==0) {
         return 1.0;
    } else {
         return x;
    }
}

sumUpTo(1) =
sumUpTo(6) =
pow(2.0, 2) =
pow(4.0, 3) =
pow(3.0,-1) =


HungryWorld

Look in the HungryWorld folder inside lab8_programs.

Harry is a hungry, but very eccentric buggle. He always starts out in the middle of the first row of a grid facing NORTHwith his brush up (can you hear his stomach rumbling?). The grid cells are randomly populated with a user-specified number of bagels, but no bagels are in the column Harry starts out in. The buggle moves row by row from the bottom to the top, and performs the following action at each row:


Initial grid configuration


Final grid configuration

Your solution must include the following four methods. You may feel free to define auxiliary methods, as necessary. Note that it may be easiest to define these methods in the reverse order than that given in order to test each method one at a time.

public void eatRows();
This method applies the eatRow method at every row in the grid as the buggle moves from the bottom row to the top row.

public void eatRow();
This method implements the row-eating behavior described by the three bullets above.

public void eatBagels();
This method eats all the bagels between the buggle and the wall it is facing. A colored square is left in every cell that originally contained a bagel. Calling this method should not change the state of the buggle.

public int countBagels();
This method returns the number of bagels between the buggle and the wall it is facing. Calling this method should not change the state of the buggle.

To see a working applet, look in the Test folder. Open the HungryWorld.html file from the Test, and experiment with HungryWorld to make sure you understand the task.


Recursion in PictureWorld: Patchwork

Download lab8_programs from the cs111d account and look in the Patchwork folder. We're going to draw some interesting patterns. Have a look at the behavior of the program in the Test subfolder. Your job is to modify the code in Patchwork.java to duplicate this behavior. Be sure your code works for zero levels.

Be careful! The code can be very simple, but the pattern is diabolical! Getting the colors to come out right is a bit tricky.