Lecture #25

1. Draw a diagram (with the triangles and arrows and such for reference types only) of the changing values (both reference and object) of variables in this code:

private static String madness(int[] a, int x, String s){

String retValue = s + "alot";

a[2] = x;

x++;

int temp = a[1];

a[1] = a[0];

a[0] = temp;

s = s + "burger";

return (x + retValue + temp);

}

public static void main(String[] args){

inti = 42;

String s = "narf";

int[] array = {1, 2, 3};

String str = madness(array, i, s);

}

Indicate the final object values of the variables:

i =s =str =array =

2. Draw a diagram (with the triangles and arrows and such) of the changing values (both reference and object) of variables in this code:

private static NaturalNumberfunTimes(NaturalNumber[] a, NaturalNumber n){

NaturalNumber local = new NaturalNumber2(5);

n.multiply(local);

n = new NaturalNumber2(17);

a[1] = n;

a[2].add(a[0]);

a[0] = new NaturalNumber2(n);

return n.divide(a[0]);

}

public static void main(String[] args){

NaturalNumbernat = new NaturalNumber2(11);

NaturalNumber[] array = new NaturalNumber2[3];

array[0] = new NaturalNumber2(4);

array[1] = new NaturalNumber2(5);

array[2] = new NaturalNumber2(6);

NaturalNumber result = funTimes(array, nat);

}

Indicate the final object values of the variables:

nat =result =array =

Lecture #27

1. Write a recursive implementation of the power method described on Slide #50. You can use either the slow approach described on Slide #51 or the fast approach described on Slide #54, but the fast approach will be more useful. Think about how you would need to change things if you were using NN’s instead of ints.

2. Write a recursive method that takes a NaturalNumber as a parameter and returns (as an int) the largest digit in that number. If the NN is 397168, it should return 9. If it’s 10, it should return 1. Use this approach: you can break the NN up into two parts, the last digit and the rest of the digits (if you use the kernel method .divideBy10(), then the last digit will be an int and the rest of the digits will be a NaturalNumber). Recursively call your method on the rest of the digits—don’t think about it, just assume it works!—to get the largest digit out of the rest of the digits. Then compare that result to the last digit from the original number and see which one is larger. Note that your method should restore the NN parameter that gets passed in.

ADVANCED: Can you think of any “shortcuts” you could add to your solution to #2 that might prevent potentially unnecessary recursive calls from being made?