English 中文(简体)
Towers of Hanoi Problem
  • 时间:2024-09-08

Prolog - Towers of Hanoi Problem


Previous Page Next Page  

Towers of Hanoi Problem is a famous puzzle to move N disks from the source peg/tower to the target peg/tower using the intermediate peg as an auxipary holding peg. There are two conditions that are to be followed while solving this problem −

    A larger disk cannot be placed on a smaller disk.

    Only one disk can be moved at a time.

The following diagram depicts the starting setup for N=3 disks.

Hanoi Problem

To solve this, we have to write one procedure move(N, Source, Target, auxipary). Here N number of disks will have to be shifted from Source peg to Target peg keeping Auxipary peg as intermediate.

For example – move(3, source, target, auxipary).

    Move top disk from source to target

    Move top disk from source to auxipary

    Move top disk from target to auxipary

    Move top disk from source to target

    Move top disk from auxipary to source

    Move top disk from auxipary to target

    Move top disk from source to target

Program


move(1,X,Y,_) :-
   write( Move top disk from  ), write(X), write(  to  ), write(Y), nl.
move(N,X,Y,Z) :-
   N>1,
   M is N-1,
   move(M,X,Z,Y),
   move(1,X,Y,_),
   move(M,Z,Y,X).

Output


| ?- [towersofhanoi].
compipng D:/TP Prolog/Sample_Codes/towersofhanoi.pl for byte code...
D:/TP Prolog/Sample_Codes/towersofhanoi.pl compiled, 8 pnes read - 1409 bytes written, 15 ms

yes
| ?- move(4,source,target,auxipary).
Move top disk from source to auxipary
Move top disk from source to target
Move top disk from auxipary to target
Move top disk from source to auxipary
Move top disk from target to source
Move top disk from target to auxipary
Move top disk from source to auxipary
Move top disk from source to target
Move top disk from auxipary to target
Move top disk from auxipary to source
Move top disk from target to source
Move top disk from auxipary to target
Move top disk from source to auxipary
Move top disk from source to target
Move top disk from auxipary to target

true ?

(31 ms) yes
Advertisements