The Lab
Original — built for the Lab

Tower of Hanoi

Move a tower of anywhere from one to 64 discs from peg A to peg C, one disc at a time, never a larger disc on a smaller one. Play it with your hands, or hand it to the recursion and watch every call light up on the way to the minimum of 2ⁿ − 1 moves.

PuzzleRecursionAlgorithmsTypeScript
Puzzle by Édouard Lucas, 1883
Loading demo…

The Tower of Hanoi looks like a toy for children and is one of the cleanest lessons in recursion there is. Nobody can hold the full move list for eight discs in their head. Almost anybody can hold this: to move eight, move the top seven out of the way, move the big one, and move the seven back on top. The seven are somebody else's problem — the same problem, one size smaller.

That is why this build has a second mode. Watch it solve and the board plays itself while a chart underneath draws every call the recursion makes. The top bar is the whole job; each row below has twice as many calls, each responsible for one fewer disc; and every call, however senior, moves exactly one disc itself. The rest it delegates. The call stack beside it is the chain of command at that instant, from the top call down to the one with its hand on a disc.

The other panel is the bill. Each extra disc doubles the work and adds one, so the minimum is 2ⁿ − 1 and the curve leaves every human scale behind quickly. The puzzle was sold with a legend of priests moving 64 golden discs, and the world ending when they finish. At one move a second, that is about 585 billion years. The page computes it rather than quoting it, and lets you buy faster priests to see how little it helps. You can also set the board to 64 and play, or let the recursion run at ten thousand moves a second and read off how long is left.

Next in the Lab
A Billionth of a DegreeOpen

A hundred pendulums dropped a billionth of a degree apart swing as one — for about nine seconds.