The Tower of Hanoi: the puzzle that teaches recursion
The Tower of Hanoi is a stack of discs on one of three pegs, biggest at the bottom. Your job is to move the whole stack to another peg. You can move only one disc at a time, and you can never put a bigger disc on a smaller one. It was invented by the French mathematician Édouard Lucas in 1883, who sold it with a made-up legend about monks moving 64 golden discs, and it has been a favourite puzzle ever since.
Start small
With one disc, it takes one move. With two discs: move the small one out of the way, move the big one, put the small one back on top. That's three moves. With three discs it takes seven moves. Try it before reading on, because the pattern is the whole secret.
The big idea
Here is how to move a stack of any size from peg A to peg C:
- Move all the discs except the biggest from A to B (using C to help).
- Move the biggest disc from A to C.
- Move the smaller stack from B onto C (using A to help).
Notice that steps 1 and 3 are the same puzzle, just one disc smaller. And to solve that smaller puzzle, you use the same three steps again, with an even smaller stack. This is called recursion: solving a problem by solving a smaller copy of itself, until the problem is so small (one disc) that the answer is obvious.
A trick you can use without thinking
If you don't want to keep the big idea in your head, there's a simple rule. Move the smallest disc on every other turn, always going round the pegs in the same direction. On the turns in between, make the only legal move that doesn't touch the smallest disc. With an odd number of discs, the smallest disc should go towards the peg you want to finish on; with an even number, it goes the other way first.
How many moves does it take?
Every extra disc doubles the work and adds one: 1, 3, 7, 15, 31, 63… The formula is 2n − 1, where n is the number of discs. Ten discs need 1,023 moves. The legend's 64 discs need 18,446,744,073,709,551,615 moves. At one move per second without ever stopping, that would take about 585 billion years, which is far longer than the universe has existed. The monks are in no danger of finishing.
The puzzle in code
Programmers love this puzzle because the recursive solution is so short. In JavaScript:
function hanoi(n, from, to, spare) {
if (n === 0) return;
hanoi(n - 1, from, spare, to); // move the smaller stack out of the way
console.log("Move disc " + n + " from " + from + " to " + to);
hanoi(n - 1, spare, to, from); // put it back on top
}
hanoi(3, "A", "C", "B");
Those few lines print the perfect solution for any number of discs. If you're learning to code, try running it with 3, then 4, and check that the number of lines printed matches 2n − 1.
Have a go
In Tower of Hanoi on the Hub, the number of discs goes up as you go, and the game tells you the best possible number of moves for each level. Try to match it, using the big idea above.