CS 051 Fall 2012

Lecture 20

Recursion Review Review

We follow four basic steps when we design recursive objects:
  1. Define an interface with all of the methods that both base case and recursive case
    classes must implement.
  2. Define one or more classes representing base cases. Make sure that all methods from
    the interface are implemented. Convince yourself that the constructors and methods work correctly.
  3. Define the constructors for recursive classes. Recursive calls of the constructor
    should only create objects that are simpler than the one being built by the constructor.
    Similarly, instance variables whose types are either the interface or class should only
    refer to objects simpler than the one being constructed. In particular, the construction
    of simpler objects in the constructor body should eventually end up at a base case.
    Convince yourself that the constructor will be correct under the assumption that the
    construction of simpler objects is correct.
  4. Write each method under the assumption that it works correctly on all simpler objects.
    Convince yourself that the methods will be correct under the assumption that instance
    variables hold simpler objects.

Chain Reaction

Our ChainReaction program recursively defines a list structure. The list is a
generic structure designed to hold other objects. We recursively define a list
as a first item on the list, and the rest of the list. The
list structure uses the constructor to add new items, and a getFirst
and getRest methods to access the components.

Towers of Hanoi Problem

The "Towers of Hanoi" problem is a classic problem in which you are given some number of disks
of different sizes, and three pins to place them on. At the beginning of the problem, all
the disks are stacked on one pin in order of size, with the smallest at the top and the largest
at the bottom.

The problem is: can you move all of the pieces so that they are in the same order on another
pin, by only moving one disk at a time? You are allowed to move any disk on top of one pin
to the top of any of the other pins, but you may never place a larger disk on top of a
smaller disk.

We discussed a recursive solution to this problem that was based on knowing a solution to the
problem with one fewer disk. If we had a solution to the (n-1) version of the problem, we can:

  1. Move top n-1 disks to the helper pin.
  2. Move the largest disk to the final pin.
  3. Move the n-1 disks from the helper pin to the final pin.

where the final pin is the pin where we want the disks to end up, and the helper pin is the other
pin that can be used in the process.

We used this solution to create our in class example: Hanoi

Recursive Powers

Another example, time permitting.
Powers program.

Here, we used a recursive definition to raise a base to a power.