CS111 Lab 8 Solutions

Total checkmarks:

Unfurling a recursive function


public static 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 and 5/3 is 1).

Other functions for practice:

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


public static 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) = 1
sumUpTo(6) = 21 (6 + 5 + 4 + 3 + 2 + 1 + 0)
pow(2,2) is 4 (or 2 * 2)
pow(4,3) is 64 (or 4 * 4 * 4)
pow(3,-1) is 0 (because 1/3 is 0.3333, which is 0 as an integer. Now, if the pow() method above had been declared as a double rather than an int method, i.e.
public static double pow(double x, int n)
then, pow(3,-1) = 0.333 because now pow() can return double precision numbers (also known as numbers that contain decimals).


HungryWorld

Click here for HungryWorld.java code. Scroll to the bottom of the file to find the four methods (eatRow(), eatRows(), eatBagels(), countBagels()). (You can also download the whole folder from cs111d: lab_solutions/lab8_solutions).

NOTE: The use of auxiliary functions can really clean up methods such as eatRow() and countBagels() so that the code is more readable.


Recursion in PictureWorld: Patchwork

Click here for Patchwork.java code. It looks so easy doesn't it!