Towers of Hanoi Problem in Prolog Language

Towers of Hanoi Problem in Prolog Language

Welcome to this blog post where we will explore some examples of cuts in Prolog programming language. Cuts are a powerful featu

re of Prolog that allow us to control the search space and prune unwanted branches of the computation tree. Cuts can also be used to implement deterministic predicates, negation, and if-then-else constructs. In this post, we will see how cuts work and how they can be used to write more efficient and elegant Prolog programs.

The Towers of Hanoi problem is a classic recursive problem often used to demonstrate the power of recursion in programming. In this problem, you have three rods (pegs) and a number of disks of different sizes, which can be stacked in decreasing size order on any rod. The goal is to move all the disks from one rod to another, with the following rules:

  1. Only one disk can be moved at a time.
  2. A larger disk cannot be placed on top of a smaller disk.

Here’s how you can solve the Towers of Hanoi problem in Prolog using recursion:

% Define the predicate to solve the Towers of Hanoi problem
hanoi(N) :-
    move(N, left, center, right).

% Base case: If there are no disks to move, do nothing.
move(0, _, _, _) :- !.

% Recursive case: Move N disks from Source to Target using the Auxiliary rod
move(N, Source, Target, Auxiliary) :-
    M is N - 1,
    move(M, Source, Auxiliary, Target), % Move N-1 disks from Source to Auxiliary
    format("Move disk ~w from ~w to ~w~n", [N, Source, Target]),
    move(M, Auxiliary, Target, Source). % Move N-1 disks from Auxiliary to Target

To use this Prolog program to solve the Towers of Hanoi problem, you can call the hanoi/1 predicate with the number of disks you want to move. For example:

?- hanoi(3).

This will output the sequence of moves required to solve the problem for three disks. You can change the argument to hanoi/1 to solve the problem for a different number of disks.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading