Write a Program in PROLOG to Solve a Tower of Hanoi Problem

Tower of Hanoi Problem in Prolog:

The ancient puzzle of the Tower of Hanoi consists of some wooden disks and three poles attached to a baseboard. The disks each have different diameters and a hole in the middle large enough for the poles to pass through.

The object of the puzzle is to move all the disks over to the right pole, one at a time, so that they end up in the original order on that pole. The middle pole may be used as a temporary resting place for disks, but at no time is a larger disk to be on top of a smaller one. The Tower of Hanoi problem can be easily solved with one or two disks but becomes more difficult with three or more disks.

A simple strategy for solving the puzzle is –

1. A single disk can be moved directly.
2. N disks can be moved in three steps:

    • i. Move N-1 disks to the middle pole.

 

    • ii. Move the last disk directly over to the right pole.

 

    iii. Move the N-1 disks from the middle pole to the right pole.

PROLOG Program to Solve a Tower of Hanoi Problem:

domains
loc=right; middle; left
predicates
hanoi(integer)
move(integer, loc, loc, loc)
inform(loc, loc)
clauses
hanoi(N):- move(N, left, middle, right).
move(1, A, _, C):- inform(A, C),!
move(N, A, B, C):-
N!=N-1, move(N1, A, C, B),
inform(A, C),
move(N1, B, A, C)
inform(LOC1, LOC2):-
write("\n Move a disk from", LOC1, "to", LOC2).