The Department of Computer Science & Engineering
|
|
STUART C. SHAPIRO: CSE
116 B
|
Recursion solves a problem by solving successively smaller instances of the same problem.
To journey n miles:
If n <= 0
Stop.
Else
Take 1 step.
Journey n miles - 1 the length of 1 step.
Stop.
To determine if the integer n is divisible by 3:
If n < 10
If n = 0, 3, 6, or 9, "yes".
Else "no".
Else
Let m be the sum of the digits of n.
If m is divisible by 3, "yes".
Else "no".
To count down from n, as asked by person p:
Say (loudly) n.
If n > 0
Ask (loudly) a neighbor to count down from n-1.
Wait for that neighbor to tell you "Done".
Say (loudly) to p, "Done".
To count up to n, as asked by person p:
If n > 0
Ask (loudly) a neighbor to count up to n-1.
Wait for that neighbor to tell you "Done".
Say (loudly) n.
Say (loudly) to p, "Done".
To move n disks from starting post, s, to destination post, d, using intermediate post, i:
If n = 1
Move the disk from s to d.
Else
Move n-1 disks from s to i using d.
Move 1 disk from s to d.
Move n-1 disks from i to d using s.
Try it