Assignment 3

Due Wednesday, July 6 at 9:00 AM

Be sure you are acquainted with my collaboration policy and my late policy, both found on the main course webpage.


  1. Suppose I have a method int num(char c) that takes a character representing a digit and returns its corresponding int. For example, num('0') returns 0, num('3') returns 3, etc. This method breaks if it is passed any character that is not a digit. Write me a method int number(String s) that takes a multi-digit numeral, uses num() and recursion, and returns the numeral's corresponding int value. You do not need to handle decimals, negative numbers, or being passed any strings containing non-digit characters (though you should handle empty strings).

  2. Write a recurrence relation for your number() method. Solve for a closed form of your relation, being sure to check your answer. Say what big-O runtime your answer represents, and explain in words why this runtime makes sense for your method.

  3. In class, we implemented the Fibonacci sequence as such:
    int fib(int n) {
    if (n==0) return 0;
    if (n==1) return 1;
    return fib(n-1) + fib(n-2);
    }
    This will give us the following recurrence relation:
    T(0) = 0
    T(1) = 1
    T(N) = 1 + T(N - 1) + T(N - 2)
    This is unlike any form we've seen before. However, notice that T(N-1) >= T(N-2). Since we are looking for the worst-case, and therefore an overestimate of our run-time, a suitable simplification would be to look at the following recurrence relation:
    T(0) = 0
    T(1) = 1
    T(N) = 1 + 2*T(N - 1)
    Solve for a closed form of this relation, being sure to check your answer, and give the big-O runtime that corresponds. Explain in words why your runtime makes sense.

  4. Read the section about the Comparable Interface in the Searching online notes. Suppose I have a class Height which has two instance variables: feet and inches. Write a method for my class of the form public int compareTo(Height other) such that if I want to compare two heights height1 and height2, height1.compareTo(height2) will return the following:

    • A negative value if height1 is less than height2
    • 0 if height1 is equal to height2
    • A positive value if height1 is greater than height2

    Describe the runtime of your method. When writing it, you may assume that other that you are being passed is indeed an instance of Height and that none of its values are null.

Turning in your work

To hand in your program, copy your answers (stored in a text file) into the following directory:

/p/course/cs367-ealexand/handin/login-name/H3

Use your actual CS login name (not your UW NetID!) in place of login-name.

You should write this assignment up by yourself. If you share ideas with anyone, be sure to cite them.


Solution

Assignment 3 Solutions