Up: Recursion. Prev: Recursion. Next: Program trace.
Using recursion often involves a key insight that makes everything simpler. Often the insight is determining what data exactly we are recursing on - we ask, what is the essential feature of the problem that should change as we call ourselves? In the case of isAJew, the feature is the person in question: At the top level, we are asking about a person; a level deeper, we ask about the person's mother; in the next level, the grandmother; and so on.
In our Towers of Hanoi solution, we recurse on the largest disk to be moved. That is, we will write a recursive function that takes as a parameter the disk that is the largest disk in the tower we want to move. Our function will also take three parameters indicating from which peg the tower should be moved (source), to which peg it should go (dest), and the other peg, which we can use temporarily to make this happen (spare).
At the top level, we will want to move the entire tower, so we want to move disks 5 and smaller from peg A to peg B. We can break this into three basic steps.
In pseudocode, this looks like the following. At the top level, we'll call MoveTower with disk=5, source=A, dest=B, and spare=C.
FUNCTION MoveTower(disk, source, dest, spare): IF disk == 0, THEN: move disk from source to dest ELSE: MoveTower(disk - 1, source, spare, dest) // Step 1 above move disk from source to dest // Step 2 above MoveTower(disk - 1, spare, dest, source) // Step 3 above END IF
Note that the pseudocode adds a base case: When disk is 0, the smallest disk. In this case we don't need to worry about smaller disks, so we can just move the disk directly. In the other cases, we follow the three-step recursive procedure we already described for disk 5.
If this doesn't make sense to you, maybe an example run will help. Even if it does make sense, run through the example to make sure you understand. Understanding the concept of recursion is important to understanding the rest of the course.
Next: Program trace.