3/6/08

To Notes

CSC 212 -- 3/6/08

 

Review Questions

  1. What is an abstract class; why would you want to use one?

    Ans: An abstract class is declared with the abstract keyword and cannot be instantiated. Its only use is to serve as the base class of another class that can be instantiated.

  2. Write an abstract class named A that defines an abstract method f with signature (String, int) and return value boolean.

  3. What is an interface; why would you want to use one?

    Ans: An interface is a specification that a class must satisfy if it is to be compatable with existing software. The class that implements the interface must provide definitions of all the methods that the interface requires.

  4. How does an interface differ from an abstract class?

    An interface only specifies required methods, it does not provide implementations. An abstract class may have abstract methods, which work exactly like the methods specified in an interface, but the abstract class may also have normal methods which have implementations that may be inherited or overridden.

  5. Write an interface definition B that requires the method g with empty signature and void return value.

  6. Draw the recursion diagram and predict the output of this method:

    public static void g(int x, int y)
    {
        if (x + y >= 1)
        {
            g(x - 1, y - 1);
            System.out.println(x + y);
            g(x - 2, y - 1);
            System.out.println(x + " " + y);
            g(x - 2, y - 2);
        } 
    }
    
  7. Show that the number of moves needed to solve the Towers of Hanoi puzzle with n disks is 2n - 1. In particular if the puzzle with 64 disks is solved at 1 second per move, the solution will take

    Ans: Proof by induction. First the base case, which is to prove the result for n = 1. In this case, the number of moves is 21 - 1 = 1.

    Next the induction case, which is to assume the result for n - 1 and prove it for n. Now the recursive solution involves moving the top n - 1 disks from the From Peg to the Aux Peg (2n-1 - 1 moves), moving the bottom ring from the From Peg to the To Peg (1 move) and moving n - 1 disks from the Aux Peg to the To Peg (2n-1 - 1 moves). The total number of moves is

  8. What is wrong with this code?

    Ans:
    1. The for loop should be

        for(int i = getCount( ); i >= 0; i--)
        
    2. There should be no semicolon at the end of the for loop line.

    3. There should be no return statement because the method is void.

  9. What is wrong with this code?

    Ans: playerA and playerB must be instantiated:

 

Project Proj6

 

More about Recursion

 

Practice Problems

  1. Predict the order in which the cells in this maze are searched.

  2. Predict the order in which the cells in this region are filled with the FloodFill algorithm.