Towers of Hanoi
The Towers of Hanoi is one of the great, canonical puzzles used in teaching recursive programming solutions.
Source: https://commons.wikimedia.org/wiki/File:Iterative_algorithm_solving_a_6_disks_Tower_of_Hanoi.gif
Here’s a video that describes the problem and its solution.
Python implementation
Here’s an implementation in Python
"""
Towers of Hanoi solver
"""
def towers_of_hanoi(n, origin, destination, auxiliary):
if n == 1:
print(f"Move disk 1 from {origin} to {destination}")
return
# Move n-1 disks from origin to auxiliary
towers_of_hanoi(n - 1, origin, auxiliary, destination)
print(f"Move disk {n} from {origin} to {destination}")
# Move n-1 disks from auxiliary to destination
towers_of_hanoi(n - 1, auxiliary, destination, origin)
# Example usage: 3 disks
n = 3
towers_of_hanoi(n, 'A', 'C', 'B')Prolog implementation
Make sure you understand the recursive solution in Python first. Once you’re certain you know how it works, give it a try in Prolog.
TipSolution (Don’t peek until you’ve had a go at it.)
/**
Towers of Hanoi solver
*/
% Base case: Move one disk directly from origin to destination
move(1, Origin, Destination, _) :-
format('Move disk 1 from ~w to ~w.', [Origin, Destination]), nl.
% Recursive case: Move N disks from origin to destination using auxiliary
move(N, Origin, Destination, Auxiliary) :-
N > 1,
M is N - 1,
move(M, Origin, Auxiliary, Destination),
format('Move disk ~w from ~w to ~w.', [N, Origin, Destination]), nl,
move(M, Auxiliary, Destination, Origin).
% Start the process with move(N, 'A', 'C', 'B') assuming A, B, and C are spindles
hanoi(N) :- move(N, 'A', 'C', 'B').
% For a solution, consult this file, and run a query indicating the
% number of disks, e.g., `?- hanoi(5).`Here’s a somewhat different solution from one of the standard texts on Prolog.