🗼
The analogy of the tower of Hanoi to programming
Last week, my math teacher, who is also my logic teacher, explained to me how computers follow instructions sequentially using the analogy of the Tower of Hanoi.
Finally, I adopted a mindset that allowed me to behave as if I were explaining something to a kid, and walkingtrhoung slowly, step by step.
Let's see:

In Java:
public class TowerOfHanoi {
// Recursive function to solve Tower of Hanoi
public static void solveHanoi(int n, char source, char destination, char auxiliary) {
// Base case: If there's only one disk, move it directly
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + destination);
return;
}
// Step 1: Move n-1 disks from source to auxiliary using destination
solveHanoi(n - 1, source, auxiliary, destination);
// Step 2: Move the nth disk from source to destination
System.out.println("Move disk " + n + " from " + source + " to " + destination);
// Step 3: Move n-1 disks from auxiliary to destination using source
solveHanoi(n - 1, auxiliary, destination, source);
}
public static void main(String[] args) {
int numberOfDisks = 4; // With 4 disks
System.out.println("Tower of Hanoi solution for " + numberOfDisks + " disks:");
solveHanoi(numberOfDisks, 'A', 'C', 'B'); // A = source, C = destination, B = auxiliary
}
}
The steps are:
- Base case: If I have only one disk, I move it directly from the source peg to the destination peg.
- Recursive step 1: I move the top
n-1
disks from the source peg to the auxiliary peg, using the destination peg as a helper. - Move largest disk: I move the remaining (largest) disk from the source peg to the destination peg.
- Recursive step 2: Then, I move the
n-1
disks from the auxiliary peg to the destination peg, using the source peg as a helper.
Our routine is already quite abstract, making it difficult to simplify things and approach them step by step. Ultimately, to paraphrase her:
"The computer is simply faster than you, not smarter"
Keep going...
<- Back to blog
All rights not reserved. Do you want a website like this? Just copy it 👍🏾