A classic puzzle solved by thinking smaller — with every move accounted for.
hanoi.pl · output · proof · check · try it in the playground
Three pegs: left, center, right. On the left peg sit three disks, largest at the bottom. Move them all to the right peg. The rules:
Which moves solve it? And can the computer show why that sequence is right?
To move a stack of N disks from one peg to another:
Moving N−1 disks is the same puzzle, only smaller. Solving a problem by reducing it to a smaller copy of itself is called recursion. One disk is the easy case: just move it.
% … two lines defining append
moves(1, From, To, _, [move(From, To)]).
moves(N, From, To, Spare, Moves) :- N > 1, Smaller is N-1, moves(Smaller, From, Spare, To, First), moves(Smaller, Spare, To, From, Last), append(First, [move(From, To)|Last], Moves).
true :+ moves(3, left, right, center, Moves).
The moves(N, …) rule is the trick, word for word: the smaller stack goes to the
spare peg (First), the big disk moves, the smaller stack follows
(Last). append glues the move lists
together.
moves(3, left, right, center, [move(left, right), move(left, center), move(right, center), move(left, right), move(center, left), move(center, right), move(left, right)]).
Seven moves, in three groups:
The proof follows the trick down to single disks:
A separate checker read the proof’s 18 steps against the program:
Verdict: checked. Nothing taken on trust.
node bin/eyedia.js examples/hanoi.pl
node bin/eyedia.js --goal "moves(2, left, right, center, Moves)" examples/hanoi.pl
The second asks for two disks: three moves, left → center, left → right, center → right. Or open it in the playground.
Change the 3 in the last line to 4: the answer grows to 15 moves.
A recursive idea — “solve the smaller puzzle, twice” — becomes a proof with the same shape: each big move list is justified by smaller ones, down to single disks that anyone can check by eye.