- Prolog - Discussion
- Prolog - Useful Resources
- Prolog - Quick Guide
- Monkey and Banana Problem
- Prolog - Linked Lists
- Towers of Hanoi Problem
- Prolog - Examples of Cuts
- Prolog - Basic Programs
- Tree Data Structure (Case Study)
- Prolog - Built-In Predicates
- Prolog - Inputs and Outputs
- Prolog - Different and Not
- Prolog - Backtracking
- Recursion and Structures
- Prolog - Lists
- Conjunctions & Disjunctions
- Loop & Decision Making
- Prolog - Operators
- Prolog - Data Objects
- Prolog - Relations
- Prolog - Basics
- Prolog - Hello World
- Prolog - Environment Setup
- Prolog - Introduction
- Prolog - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Prolog - Towers of Hanoi Problem
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](/prolog/images/hanoi_problem.jpg)
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) yesAdvertisements