← Algorithms · Lesson 10/11
The Tower of Hanoi
The puzzle and its two rules
Three pegs and a tower of disks, from the biggest at the bottom to the smallest on top. You have to move the whole tower to another peg with two rules:
- You move one disk at a time: the top one of some peg.
- A big disk never goes on a small one.
The French mathematician Édouard Lucas invented it in 1883, and presented it as the discovery of one "N. Claus de Siam", an anagram of "Lucas d'Amiens".
Each peg is a stack: you only touch the top disk. In JavaScript, an array with push and pop.
-
1the disks, from 1 (the small one) to 3 -
xpegs A, B and C
$ node leccion.js
Press RUN (or Ctrl+Enter).
What to look at
- The second move isn't allowed: 1 is already on top of C.
- After three good moves, the two small ones are on B and 3 is free on A. That's exactly half of the trick.
The whole lesson on one page
The puzzle and its two rules
Three pegs and a tower of disks, from the biggest at the bottom to the smallest on top. You have to move the whole tower to another peg with two rules:
- You move one disk at a time: the top one of some peg.
- A big disk never goes on a small one.
The French mathematician Édouard Lucas invented it in 1883, and presented it as the discovery of one "N. Claus de Siam", an anagram of "Lucas d'Amiens".
Each peg is a stack: you only touch the top disk. In JavaScript, an array with push and pop.
-
1the disks, from 1 (the small one) to 3 -
xpegs A, B and C
// the three pegs; the last item of each array is the top disk
const postes = { A: [3, 2, 1], B: [], C: [] };
function mover(desde, hasta) {
const disco = postes[desde].at(-1);
const debajo = postes[hasta].at(-1);
if (debajo !== undefined && debajo < disco) {
console.log("not allowed: " + disco + " on top of " + debajo);
return;
}
postes[hasta].push(postes[desde].pop());
console.log(disco + ": " + desde + " → " + hasta, JSON.stringify(postes));
}
mover("A", "C");
mover("A", "C"); // 2 on top of 1
mover("A", "B");
mover("C", "B");
- The second move isn't allowed: 1 is already on top of C.
- After three good moves, the two small ones are on B and 3 is free on A. That's exactly half of the trick.
The trick: move n − 1, the big one, and n − 1 again
To move n disks from desde (from) to hasta (to), the big one at the bottom has to reach hasta first, and for that the n − 1 above it have to be on the third peg, aux (spare). So:
1. Move the top n − 1 from desde to aux. 2. Move the big one to hasta. 3. Move the n − 1 from aux to hasta, on top of the big one.
Steps 1 and 3 are the same problem with one disk fewer: the function calls itself. And with zero disks there's nothing to move: that's the base case, which stops the recursion.
This is the code from the video; mover (move) only prints.
// prints one move
const mover = (n, desde, hasta) => console.log("disk " + n + ": " + desde + " → " + hasta);
function hanoi(n, desde, hasta, aux) {
if (n === 0) return;
hanoi(n - 1, desde, aux, hasta);
mover(n, desde, hasta);
hanoi(n - 1, aux, hasta, desde);
}
hanoi(3, "A", "C", "B");
- Seven moves. Disk 3 moves only once, right in the middle: before it, the two on top went to B (the first three); after it, they come back on top (the last three).
- Change the 3 to 4: you get 15.
The call stack
When hanoi(3, …) calls hanoi(2, …), the 3-call doesn't finish: it waits on the call stack, along with the line it was on, until the 2-call is done. The 2-call waits for the 1-call, and the 1-call for the 0-call, which returns right away. The last one in is the first one out.
The program builds that stack by hand, with an array, so you can see it: each line is the stack at the moment a call comes in. It's the same function with the base case written the other way around (if (n > 0)), so pila.pop() runs in both cases.
const pila = []; // the call stack, built by hand so you can see it
function hanoi(n, desde, hasta, aux) {
pila.push("hanoi(" + n + "," + desde + "," + hasta + "," + aux + ")");
console.log(pila.join(" "));
if (n > 0) {
hanoi(n - 1, desde, aux, hasta);
console.log(" move disk " + n + ": " + desde + " → " + hasta);
hanoi(n - 1, aux, hasta, desde);
}
pila.pop();
}
hanoi(2, "A", "C", "B");
- The stack grows to three calls (2, 1 and 0) and shrinks every time one finishes.
hanoi(2, …)heads every stack line: it waits from start to finish. - With two disks there are 7 calls in all, but never more than 3 at once. With n disks, never more than n + 1: the stack takes O(n) even though the work is much more.
How many moves? 2ⁿ − 1
Moving n disks is moving n − 1, one more, and n − 1 again: double what n − 1 takes, plus one. With 1 disk it's 1 move; with 2, 3; with 3, 7; with 4, 15… Always one less than a power of 2: 2ⁿ − 1. And you can't do it in fewer: the big disk can't move until all the others are together on another peg, so any solution goes through a tower of n − 1 twice.
It's O(2ⁿ): each extra disk doubles the work. Recursion doesn't make it slow; the problem really is that big.
let movimientos = 0, llamadas = 0, alto = 0, altoMax = 0;
const mover = () => movimientos++;
function hanoi(n, desde, hasta, aux) {
llamadas++; alto++; altoMax = Math.max(altoMax, alto);
if (n > 0) {
hanoi(n - 1, desde, aux, hasta);
mover(n, desde, hasta);
hanoi(n - 1, aux, hasta, desde);
}
alto--;
}
for (const n of [1, 2, 3, 4, 10, 20]) {
movimientos = llamadas = altoMax = 0;
hanoi(n, "A", "C", "B");
console.log("n =", n, "| moves:", movimientos, "| 2^n - 1:", 2 ** n - 1, "| calls:", llamadas, "| stack:", altoMax);
}
- The moves count exactly like
2 ** n - 1: with 20 disks, over a million. - The calls are 2ⁿ⁺¹ − 1 (each one that moves makes two more), but the stack never goes past n + 1.
The legend of the 64 disks
The puzzle came with a legend: in a temple, priests move a tower of 64 golden disks following these same rules, and when they finish, the world will end. (There are versions with another place and another number of disks.)
No need to rush. It takes 2⁶⁴ − 1 moves: at one per second, about 585 billion years, some 42 times the age of the universe. Not even a computer making a billion moves per second would finish in under 500 years.
A JavaScript detail: 2⁶⁴ − 1 no longer fits exactly in a Number, which keeps about 16 digits. To count it without losing any there's BigInt, the numbers with an n at the end.
const movimientos = 2n ** 64n - 1n; // BigInt: exact
console.log("moves:", movimientos.toString());
console.log("as a Number:", 2 ** 64 - 1); // gets rounded
const anio = 365.25 * 24 * 60 * 60; // seconds in a year
const segundos = Number(movimientos);
console.log("years at one per second:", Math.round(segundos / anio));
console.log("years at a billion per second:", Math.round(segundos / 1e9 / anio));
- 18,446,744,073,709,551,615 moves; the
Numberends in …552000: it lost the last digits. - 584,542,046,091 years, which round to 585 billion. At a billion per second, 585 years.