Want:
Move disk from peg 1 to peg 2
Move disk from peg 1 to peg 3
Move disk from peg 2 to peg 3
How to move largest disk from peg 1 to peg 3?
Step 1: Move subtower to peg 2
Step 2: Move bottom disk to peg 3
Step 3: Move subtower to peg 3
How do we move \(m\) disks from peg \(i\) to peg \(j\)?
To move \(m\) disks from peg \(i\) to \(j\):
What is missing?
If \(m = 1\), just print
Move disk from peg i to peg j
void move (int m, int from, int to, int other) {
if (m == 1) {
System.out.println("Move disk from " + from + " to " + to);
return;
}
move(m - 1, from, other, to);
move(1, from, to, other);
move(m - 1, other, to, from);
}
If \(f(m )\) is number of instructions printed to move \(m\) disks:
Solving Tower of Hanoi with $m$ disks requires $2^m - 1$ instructions!
private static int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
private static int fibonacci (int n) {
if (n <= 2) return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
private static void move (int num, int from, int to, int other) {
if (num == 1) {
System.out.println("Move disk from " + from + " to " + to + "." );
return;
}
move(num - 1, from, other, to);
move(1, from, to, other);
move(num - 1, other, to, from);
}
Recursion is…
public static long collatz (long n) {
if (n == 1) return 1;
if (n % 2 == 0) return collatz (n / 2);
else return collatz (3 * n + 1);
}
public static long collatz (long n) {
if (n == 1) return 1;
if (n % 2 == 0) return collatz (n / 2);
else return collatz (3 * n + 1);
}
n