0% found this document useful (0 votes)
25 views45 pages

Ailabamit

Uploaded by

uritvik0728
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views45 pages

Ailabamit

Uploaded by

uritvik0728
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

LIST OF PROGRAMS

Subject: Artificial Intelligence Lab Code: KCS-751A

MAPPING WITH
S.NO. NAME OF EXPERIMENT
CO
1 Study of PROLOG.Write the following programs using PROLOG C405.1
2 Write a program in prolog to implement simple facts and Queries C405.1
3 Write a program in prolog to implement simple arithmetic C405.4
4 Write a program in prolog to solve Monkey banana problem C405.2
5 Write a program in prolog to solve Tower of Hanoi C405.2
6 Write a program in prolog to solve 8 Puzzle problems C405.3
7 Write a program in prolog to solve 4-Queens problem C405.1
8 Write a program in prolog to solve Traveling salesman problem C405.3
9 Write a program in prolog for Water jug problem C405.5
10 Program to categorize animal characteristics. C405.5
VALUE ADDED PROGRAMS
11 Write a program to implement a Tic-Tac-Toe game. C405.3

12 Write a program to solve 8 queens’problem C405.3


13 Program to demonstrate family relationship. C405.2
14 Program to show concept of list. C405.4

5
PRACTICAL -1

AIM: Study of PROLOG.Write the following programs using PROLOG

PROLOG-PROGRAMMING IN LOGIC

PROLOG stands for Programming, In Logic — an idea that emerged in the early 1970’s to
use logic as programming language. The early developers of this idea included Robert
Kowaiski at Edinburgh (on the theoretical side), Marrten van Emden at Edinburgh
(experimental demonstration) and AlianColmerauer at Marseilles (implementation).

David D.H. Warren’s efficient implementation at Edinburgh in the mid -1970’s greatly
contributed to the popularity of PROLOG. PROLOG is a programming language centred
around a small set of basic mechanisms, including pattern matching, tree based data
structuring and automatic backtracking. This Small set constitutes a surprisingly powerful
and flexible programming framework. PROLOG is especially well suited for problems that
involve objects- in particular, structured objects- and relations between them.

SYMBOLIC LANGUAGE

PROLOG is a programming language for symbolic, non-numeric computation. It is


especially well suited for solving problems that involve objects and relations between objects.
For example, it is an easy exercise in prolog to express spatial relationship between objects,
such as the blue sphere is behind the green one. It is also easy to state a more general rule: if
object X is closer to the observer than object Y. and object Y is closer than Z, then X must be
closer than Z. PROLOG can reason about the spatial relationships and their consistency with
respect to the general rule. Features like this make PROLOG a powerful language for
ArtJIcia1 LanguageA1,) and non- numerical programming.

There are well-known examples of symbolic computation whose implementation in other


standard languages took tens of pages of indigestible code, when the same algorithms were
implemented in PROLOG, the result was a crystal-clear program easily fitting on one page.

FACTS, RULES AND QUERIES

Programming in PROIOG is accomplished by creating a database of facts and rules about


objects, their properties, and their relationships to other objects. Queries then can be posed
about the objects and valid conclusions will be determined and returned by the program
Responses to user queries are determined through a form of inference control known as
resolution.
6
FOR EXAIPLE:

a) FACTS:

Some facts about family relationships could be written as:

sister (sue,bill)

parent (ann.sam)

male(jo)

female(riya)

b) RULES:

To represent the general rule for grandfather, we write:

grandfather(X2)

parent(X,Y)

parent( Y,Z)

male(X)

c) QUERIES:

Given a database of facts and rules such as that above, we may make queries by typing after a
query a symbol’?’ statements such as:

?-parent(X,sam) Xann

?grandfather(X,Y)

X=jo, Y=sam

PROLOG IN DISGINING EXPERT SYSTEMS

An expert system is a set of programs that manipulates encoded knowledge to solve problems
in a specialized domain that normally requires human expertise. An expert system’s
knowledge is obtained from expert sources such as texts, journal articles. databases etc and
encoded in a form suitable for the system to use in its inference or reasoning processes. Once
a sufficient body of expert knowledge has been acquired, it must be encoded in some form,
loaded into knowledge base, then tested, and refined continually throughout the life of the
7
system PROLOG serves as a powerful language in designing expert systems because of its
following features.

• Use of knowledge rather than data


• Modification of the knowledge base without recompilation of the control programs.
• Capable of explaining conclusion.
• Symbolic computations resembling manipulations of natural language.
• Reason with meta-knowledge.

META PROGRAMMING

A meta-program is a program that takes other programs as data. Interpreters and compilers
are examples of mela-programs. Meta-interpreter is a particular kind of meta-program: an
interpreter for a language written in that language. So a PROLOG interpreter is an interpreter
for PROLOG, itself written in PROLOG. Due to its symbol- manipulation capabilities,
PROLOG is a powerful language for meta-programming. Therefore, it is often used as an
implementation language for other languages. PROLOG is particularly suitable as a language
for rapid prototyping where we are interested in implementing new ideas quickly. New ideas
are rapidly implemented and experimented with.

Code/Method:

Program to demonstrate a simple prolog program.

% Predicates declaration (Optional in Prolog, used for clarity)


% like(Symbol1, Symbol2) - denotes that Symbol1 likes Symbol2.
% hate(Symbol1, Symbol2) - denotes that Symbol1 hates Symbol2.

% Facts about "like"


like(sita, ram). % Sita likes Ram
like(x, y). % x likes y
like(a, b). % a likes b

% Facts about "hate"


hate(c, d). % c hates d
hate(m, n). % m hates n
hate(f, g). % f hates g

8
Output:

9
PRACTICAL -2

AIM: Write a program in prolog to implement simple facts and Queries.

Procedure:
1. Ram likes mango.
2. Seema is a girl.
3. Bill likes Cindy.
4. Rose is red.
5. John owns gold.

Code/Method:

% Facts
likes(ram, mango).
likes(bill, cindy).

girl(seema).

red(rose).

owns(john, gold).

% Query Example:
% ?- likes(ram, What).
% Expected Output:
% What = mango.

10
Output:

11
PRACTICAL -3

AIM: Write a program to implement simple arithmetic.

Procedure:
Arithmetic

Prolog must be able to handle arithmetic in order to be a useful general


purpose programming language. However, arithmetic does not fit nicely into
the logical scheme of things.

That is, the concept of evaluating an arithmetic expression is in contrast to the


straight pattern matching we have seen so far. For this reason, Prolog provides
the built-in predicate 'is' that evaluates arithmetic expressions. Its syntax calls
for the use of operators.

X is <arithmetic expression>

The variable X is set to the value of the arithmetic expression. On


backtracking it is unassigned.

The arithmetic expression looks like an arithmetic expression in any other


programming language.

Here is how to use Prolog as a calculator.

?- X is 2 + 2.
X=4

?- X is 3 * 4 + 2.
X = 14

Parentheses clarify precedence.

?- X is 3 * (4 + 2).
X = 18

12
?- X is (8 / 4) / 2. X=1

In addition to 'is,' Prolog provides a number of operators that compare two


numbers. These include 'greater than', 'less than', 'greater or equal than', and
'less or equal than.' They behave more logically, and succeed or fail according
to whether the comparison is true or false. Notice the order of the symbols in
the greater or equal than and less than or equal operators. They are specifically
constructed not to look like an arrow, so that you can use arrow symbols in
your programs without confusion.

X>Y
X<Y
X >= Y
X =< Y

Here are a few examples of their use.

?- 4 > 3.
Yes
?- 4 < 3.
No
?- X is 2 + 2, X > 3.
X=4
?- X is 2 + 2, 3 >= X.
No
?- 3+4 > 3*2.
Yes

Code/Method:

% Rule to convert Celsius to Fahrenheit


c_to_f(C, F) :-
F is C * 9 / 5 + 32.

% Rule to check if the temperature is freezing (<= 32�F)


freezing(F) :-
F =< 32.

13
Output:

14
PRACTICAL -4

AIM: Write a program to solve the Monkey Banana problem

Procedure:

Imagine a room containing a monkey, chair and some bananas. That have been hanged from
the center of ceiling. If the monkey is clever enough, he can reach the bananas by placing the
chair directly below the bananas and climb on the chair. The problem is to prove the monkey
can reach the bananas. The monkey wants it, but cannot jump high enough from the floor. At
the window of the room there is a box that the monkey can use. The monkey can perform the
following actions: -
1) Walk on the floor.
2) Climb the box.
3) Push the box around (if it is beside the box).
4) Grasp the banana if it is standing on the box directly under the banana.

Production Rules

can_reach clever,close.

get_on: can_climb.

under in room,in_room, in_room,can_climb.

Close get_on,under| tall

15
Code/Method:

% Facts
in_room(bananas). % Bananas are in the room.
in_room(chair). % Chair is in the room.
in_room(monkey). % Monkey is in the room.
clever(monkey). % Monkey is clever.
can_climb(monkey, chair). % The monkey can climb the chair.
tall(chair). % The chair is tall enough for the monkey to reach
the bananas.
can_move(monkey, chair, bananas). % The monkey can move the chair under the
bananas.

% Rules
can_reach(X, Y) :-
clever(X),
is_close(X, Y). % The monkey can reach the bananas if it is
clever and close enough.

get_on(X, Y) :-
can_climb(X, Y). % The monkey can get on the chair if it can climb
it.

under(chair,bananas) :-
in_room(chair),
in_room(bananas),
tall(chair).

is_close(X, Z) :-
get_on(X, Y),
under(Y, Z). % The monkey is close

16
Output:

17
PRACTICAL -5

AIM: Write a program to solve the Tower of Hanoi problem.

Procedure:

This object of this famous puzzle is to move N disks from the left peg to the right peg
using thecenter peg as an auxiliary holding peg. At no time can a larger disk be
placed upon a smallerdisk.Thefollowingdiagramdepictsthestarting setupforN=3disks.

Production Rules
hanoi(N) move(N,left,middle,right).
move(1,A,_,C) inform(A,C),fail.
move(N,A,B,C) N1=N-1,move(N1,A,C,B),inform(A,C),move(N1,B,A,C).

ParseTree:-

18
Code/Method:

% Main predicate to solve the Tower of Hanoi


hanoi(N) :-
move(N, left, middle, right).

% Move one disk from source (A) to destination (C)


move(1, A, _, C) :-
inform(A, C), !.

% Move N disks from source (A) to destination (C) using an auxiliary peg (B)
move(N, A, B, C) :-
N1 is N - 1, % Use 'is' for arithmetic operation
move(N1, A, C, B), % Move N-1 disks from A to B using C as
auxiliary
inform(A, C), % Move the top disk from A to C
move(N1, B, A, C). % Move N-1 disks from B to C using A as
auxiliary

% Inform about a disk move


inform(Loc1, Loc2) :-
write('Move a disk from '),
write(Loc1),
write(' to '),
write(Loc2),
nl. % Newline after each move for better readability

19
Output:

20
PRACTICAL -6

AIM: Write a program to solve the 8-Puzzle problem.

Procedure:

The title of this section refers to a familiar and popular sliding tile puzzle that has been
aroundfor at least forty years. The most frequent older versions of this puzzle have numbers
or lettersanthesliding tiles, andthe player is supposedtoslide tilesinto newpositions
inordertorealign a scrambled puzzle back into a goal alignment. For illustration, we use the 3
x 3 8-tileversion,whichisdepicted hereingoal configuration.

7 2 3
4 6 5

1 8

To represent these puzzle "states" we will use a Prolog term representation employing '/' as a
separator. The positions of the tiles are listed (separated by '/') from top to bottom, and from
left to right. Use "0" to represent the empty tile (space). For example, the goal is ... goal
(1/2/3/8/0/4/7/6/5).
Code/Method:

target( [[ [] ,0 ,1],
[ 2 ,3 ,4],
[ 5 ,6 ,7]]).

from( [[6 ,1 ,3],


[4 ,[] ,5],
[7 ,2 ,0]]).

% A *backtrackable* predicate which proposes a new position (RowNew,ColNew)


% for the hole at position (Row,Col). The hole is moved in direction
% MoveDirection
% This is not as nice as pattern matching over a pair of

21
% states because you can't make it run "backwards" to determine a
% move and input matrix from an output matrix.

% new_hole_position(Row,Col,RowNew,ColNew,MoveDirection)

new_hole_position(Row,Col,RowNew,Col,down) :- Row < 2, RowNew is Row+1.


new_hole_position(Row,Col,RowNew,Col,up) :- Row > 0, RowNew is Row-1.
new_hole_position(Row,Col,Row,ColNew,right) :- Col < 2, ColNew is Col+1.
new_hole_position(Row,Col,Row,ColNew,left) :- Col > 0, ColNew is Col-1.

% Pick the value at (Row,Col) from MatrixIn into ValOld and


% Put ValNew at (Row,Col), giving MatrixOut. This is used to
% generate a new state from an existing state and a "hole move".

pick_and_put_matrix(Row,Col,MatrixIn,ValOld,ValNew,MatrixOut) :-
pick_and_put(Row,MatrixIn,RowlistOld,RowlistNew,MatrixOut),
pick_and_put(Col,RowlistOld,ValOld,ValNew,RowlistNew).

pick_and_put(Index,ListIn,ValOld,ValNew,ListOut) :-
length(Prefix,Index),
append([Prefix,[ValOld],Suffix],ListIn),
append([Prefix,[ValNew],Suffix],ListOut),
!.

% Moving the hole from (Row,Col) to (RowNew,ColNew)

move_hole(Row,Col,RowNew,ColNew,MatrixIn,MatrixOut) :-
pick_and_put_matrix(Row,Col,MatrixIn,[],Val,MatrixMid),
pick_and_put_matrix(RowNew,ColNew,MatrixMid,Val,[],MatrixOut).

% Find out where the hole is in MatrixIn as we don't


% keep track of that information.

cur_hole_position(Row,Col,MatrixIn) :-
nth0(Row,MatrixIn,RowList),
cur_hole_position_in_row(Col,RowList),!.

cur_hole_position_in_row(Col,RowList) :-
nth0(Col,RowList,[]).

% For showing off, the number of states visited is counted in


% a thread-local variable that is non-backtrackably incremented.

22
nb_inc_counter :-
nb_getval(counter,X),
XX is X+1,
nb_setval(counter,XX).

% The search proper. Perform a single move from one state (matrix)
% to the next state (matrix)
%
% move(+CurrentState,+GoalState,
% -SolutionAsGrowingOpenListToWhichOneAppends
% +StatesOnPathSoAsToNotVisitAStateTwiceToWhichOnePrepends,
% +DepthCountdownForIterativeDeepening)

move(Matrix,Matrix,[],_,_) :- !.
move(MatrixIn,MatrixTarget,[MatrixMid|Moves],MatrixesOnPath,Depth) :-
Depth > 1,
nb_inc_counter,
cur_hole_position(Row,Col,MatrixIn),
new_hole_position(Row,Col,RowNew,ColNew,_MoveDirection),
move_hole(Row,Col,RowNew,ColNew,MatrixIn,MatrixMid),
\+ member(MatrixMid,MatrixesOnPath),
SmallerDepth is Depth-1,
move(MatrixMid,MatrixTarget,Moves,[MatrixMid|MatrixesOnPath],SmallerDepth).

% Printout curclicues

print_and_reset_counter :-
nb_getval(counter,C),
(C>0
-> format("Examined ~d positions~n",[C])
; true),
nb_setval(counter,0).

format_moves([Matrix],_) :-
format_matrix(Matrix).
format_moves([Matrix,Matrix2|Moves],Index) :-
format_matrix(Matrix),
format("Move ~d~n",[Index]),
Index2 is Index+1,
format_moves([Matrix2|Moves],Index2).

23
format_matrix([[A,B,C],[D,E,F],[G,H,I]]) :-
enlarge(A,AE),
enlarge(B,BE),
enlarge(C,CE),
enlarge(D,DE),
enlarge(E,EE),
enlarge(F,FE),
enlarge(G,GE),
enlarge(H,HE),
enlarge(I,IE),
format("+--------+~n",[]),
format("|~s,~s,~s|~n",[AE,BE,CE]),
format("|~s,~s,~s|~n",[DE,EE,FE]),
format("|~s,~s,~s|~n",[GE,HE,IE]),
format("+--------+~n",[]).

enlarge(X,XE) :-
format(string(S)," ~q",[X]),
sub_string(S,_,2,0,XE).

% "Main" predicate.

run(Moves) :-
from(MatrixFrom),
target(MatrixTarget),
nb_setval(counter,0),
between(1,30,MaxDepth), % backtrackable; iterative deepening
print_and_reset_counter,
format("Maximum depth is ~d~n",[MaxDepth]),
move(MatrixFrom,MatrixTarget,Moves,[MatrixFrom],MaxDepth),
announce_success([MatrixFrom|Moves]).

announce_success(Moves) :-
length(Moves,Length),
AdjustedLength is Length-1,
nb_getval(counter,C),
format("Found a solution of ~d moves by examination of ~d
positions.~n",[AdjustedLength,C]),
format_moves(Moves,1).

24
ThePrologprogramfromtheprevioussectionandtheprogramoutlinedinthissectioncanbeusedas
an8-puzzlesolver.

?- solve(0/8/1/2/4/3/7/6/5, S).

25
Output:

26
PRACTICAL -7

AIM: Write a program to solve the 4-Queen problem.

Procedure:

Inthe4 Queensproblemtheobjectistoplace4queensona chessboardin suchawaythat


noqueens can capture a piece. This means that no two queens may be placed on the
same row,column,ordiagonal.

TheNQueensChessboard

Code/Method:
% Domain for queen
queen(q(Row, Col)).

% List of all possible row and column positions


makelist(1, [1]).
makelist(N, [N|Rest]) :-
N1 is N - 1,
makelist(N1, Rest).

% Find and remove an element from the list


findandremove(_, [], []).
findandremove(X, [X|Rest], Rest).
findandremove(X, [Y|Rest], [Y|Tail]) :-
findandremove(X, Rest, Tail).
27
% Place N queens on the board
nqueens(N) :-
makelist(N, Rows),
Diagonal is N * 2 - 1,
makelist(Diagonal, Diag),
placeN(N, board([], Rows, Rows, Diag, Diag), FinalBoard),
write(FinalBoard).

% Base case: when no more queens need to be placed


placeN(_, board(Queens, [], [], Diag1, Diag2), board(Queens, [], [], Diag1,
Diag2)) :- !.

% Recursive case: place a queen on the board


placeN(N, Board1, Result) :-
place_a_queen(N, Board1, Board2),
placeN(N, Board2, Result).

% Place a queen on the board and update the board


place_a_queen(N, board(Queens, Rows, Columns, Diag1, Diag2), board([q(R,
C)|Queens], NewRows, NewCols, NewDiag1, NewDiag2)) :-
nextrow(R, Rows, NewRows),
findandremove(C, Columns, NewCols),
D1 is N + C - R,
findandremove(D1, Diag1, NewDiag1),
D2 is R + C - 1,
findandremove(D2, Diag2, NewDiag2).

% Remove a row from the list of available rows


nextrow(Row, [Row|Rest], Rest).

% Example query:
% ?- nqueens(4), nl.

28
Output:

29
PRACTICAL -8

AIM: Write a program to solve the traveling salesman problem.

Procedure:
Thefollowingisthesimplifiedmapusedfortheprototype:

Code:
% Define roads between towns (facts)
road("tampa", "houston", 200).
road("houston", "tampa", 200).
road("gordon", "tampa", 300).
road("tampa", "gordon", 300).
road("houston", "gordon", 100).
road("gordon", "houston", 100).
road("houston", "kansas_city", 120).
road("kansas_city", "houston", 120).
road("gordon", "kansas_city", 130).
road("kansas_city", "gordon", 130).

% Base rule to find the direct route between two towns.


route(Town1, Town2, Distance) :-
road(Town1, Town2, Distance).
30
% Recursive rule to find the route between two towns, where there's an
intermediate town.
route(Town1, Town2, Distance) :-
road(Town1, Intermediate, Dist1),
route(Intermediate, Town2, Dist2),
Distance is Dist1 + Dist2.

% Held-Karp Dynamic Programming to find the shortest route


% dp(Bitmask, LastTown, Distance) - The minimum distance required to visit all
towns in the bitmask, ending at LastTown
dp(Bitmask, Town, Distance) :-
travel(Bitmask, Town, Distance).

% Base case for the DP (when only the starting city is visited)
travel(1 << 0, 0, 0). % Starting from town 0 (first town), distance is 0

% Recursive case for calculating distances


travel(Bitmask, LastTown, MinDistance) :-
% Try all possible previous towns that could lead to LastTown
BitmaskWithoutLast = Bitmask - (1 << LastTown),
travel(BitmaskWithoutLast, PrevTown, DistToPrev),
route(PrevTown, LastTown, DistToLast),
MinDistance is DistToPrev + DistToLast.

% To find the shortest route, we check all possible last towns


find_shortest_route(Towns, ShortestDistance) :-
length(Towns, N),
% Create a list of 0 to N-1 for all towns
findall(Town, between(0, N-1, Town), TownList),
% Initialize bitmask (all towns not yet visited, except the starting town)
travel(0, TownList, ShortestDistance).

31
Output:

32
PRACTICAL -9

AIM: Write a program for water jug problem

Procedure:

"You are given two jugs, a 4-gallon one and a 3-gallon one. Neither have any
measuring markerson it. There is a tap that can be used to fill the jugs with water.
How can you get exactly 2gallonsofwaterintothe4-gallonjug?".

Production Rules: -

R1: (x,y) --> (4,y) if x < 4


R2: (x,y) --> (x,3) if y < 3
R3: (x,y) --> (x-d,y) if x > 0
R4: (x,y) --> (x,y-d) if y > 0
R5: (x,y) --> (0,y) if x > 0
R6: (x,y) --> (x,0) if y > 0
R7: (x,y) --> (4,y-(4-x)) if x+y>= 4 and y > 0
R8: (x,y) --> (x-(3-y),y) if x+y>= 3 and x > 0
R9: (x,y) --> (x+y,0) if x+y =< 4 and y > 0
R10: (x,y) --> (0,x+y) if x+y =< 3 and x > 0

Code:

% Define the base case for the goal


goal_state(2, _) :- % We want exactly 2 gallons in the 4-gallon jug
write('Goal reached: 4-gallon jug has 2 gallons\n').

% Check for already visited states to avoid infinite loops


visited(State, Visited) :-
member(State, Visited).

% Maneuver function that generates all possible transitions and prevents


revisiting states
maneuver(X, Y, Visited) :-
goal_state(X, Y), % If we reach the goal state, stop and print the
message
!.

33
maneuver(X, Y, Visited) :-
% Fill the 4 gallon jug if it's not already full
X < 4,
\+ visited((4, Y), Visited),
append(Visited, [(4, Y)], NewVisited),
write('Fill 4 gallon jug\n'),
maneuver(4, Y, NewVisited).

maneuver(X, Y, Visited) :-
% Fill the 3 gallon jug if it's not already full
Y < 3,
\+ visited((X, 3), Visited),
append(Visited, [(X, 3)], NewVisited),
write('Fill 3 gallon jug\n'),
maneuver(X, 3, NewVisited).

maneuver(X, Y, Visited) :-
% Empty the 4 gallon jug if it's not empty
X > 0,
\+ visited((0, Y), Visited),
append(Visited, [(0, Y)], NewVisited),
write('Empty the 4 gallon jug\n'),
maneuver(0, Y, NewVisited).

maneuver(X, Y, Visited) :-
% Empty the 3 gallon jug if it's not empty
Y > 0,
\+ visited((X, 0), Visited),
append(Visited, [(X, 0)], NewVisited),
write('Empty the 3 gallon jug\n'),
maneuver(X, 0, NewVisited).

maneuver(X, Y, Visited) :-
% Pour from 3 gallon jug to 4 gallon jug
X + Y >= 4, Y > 0,
K is 4 - X,
M is Y - K,
\+ visited((4, M), Visited),
append(Visited, [(4, M)], NewVisited),
write('Pour from 3 gallon jug to 4 gallon jug\n'),
maneuver(4, M, NewVisited).

34
maneuver(X, Y, Visited) :-
% Pour from 4 gallon jug to 3 gallon jug
X + Y >= 3, X > 0,
K is 3 - Y,
M is X - K,
\+ visited((M, 3), Visited),
append(Visited, [(M, 3)], NewVisited),
write('Pour from 4 gallon jug to 3 gallon jug\n'),
maneuver(M, 3, NewVisited).

maneuver(X, Y, Visited) :-
% Pour the water in the 3 gallon jug into the 4 gallon jug if it fits
X + Y =< 4, Y > 0,
\+ visited((X + Y, 0), Visited),
append(Visited, [(X + Y, 0)], NewVisited),
write('Pour the water in the 3 gallon jug into the 4 gallon jug\n'),
maneuver(X + Y, 0, NewVisited).

maneuver(X, Y, Visited) :-
% Pour the water in the 4 gallon jug into the 3 gallon jug if it fits
X + Y =< 3, X > 0,
\+ visited((0, X + Y), Visited),
append(Visited, [(0, X + Y)], NewVisited),
write('Pour the water in the 4 gallon jug into the 3 gallon jug\n'),
maneuver(0, X + Y, NewVisited).

% Wrapper to start the process and ensure initial state is handled


solve_jugs :-
initial_state(X, Y),
write('Initial State: 0 gallons in 4-gallon jug and 0 gallons in 3-gallon
jug\n'),
maneuver(X, Y, []).

% Initial state of the jugs: both jugs are empty


initial_state(0, 0).

35
Output:

36
PRACTICAL -10

AIM: Write a program to categorize animal characteristics.

Procedure:
A simple program to categorize animal based on their characteristics. Provide some
simplefacts and make queries on them.
Code/Method:
% Define the characteristics of animals

% Size characteristics
small(rat).
small(cat).
large(lion).

% Color characteristics
color(dog, black).
color(rabbit, white).

% Dark color can be either black or brown


color(X, dark) :-
color(X, black);
color(X, brown).

% Queries can be made to check an animal's size and color.


% Example Queries:
% ?- small(X).
% ?- color(rabbit, X).
% ?- color(X, dark).

37
Output:

38
VALUE ADDED PROGRAMS

39
PRACTICAL -11

AIM: Write a program to implement a Tic-Tac-Toe game.

Procedure:

In the Tic Tac Toe computer program the player chooses if they want to be X or O. Whotakes
the first turn is randomly chosen. Then the player and computer take turns makingmoves. The
boxes on the left side of the flowchart are what happens during the player’sturn.The right side
shows what happens on the computer's turn. After the player orcomputermakes a move, the
program checks if they won or caused a tie, and then thegame switchesturn. After the game is
over, the program asks the player if they want toplayagain.

Code/Method:

% A Tic-Tac-Toe program in Prolog.


% To play a game with the computer, type
% playo.
% To watch the computer, play a game with itself, type
% selfgame.
%

% Predicates that define the winning conditions:

win(Board, Player) :- rowwin(Board, Player).


win(Board, Player) :- colwin(Board, Player).
win(Board, Player) :- diagwin(Board, Player).

rowwin(Board, Player) :- Board = [Player,Player,Player,_,_,_,_,_,_].


rowwin(Board, Player) :- Board = [_,_,_,Player,Player,Player,_,_,_].
rowwin(Board, Player) :- Board = [_,_,_,_,_,_,Player,Player,Player].

colwin(Board, Player) :- Board = [Player,_,_,Player,_,_,Player,_,_].


colwin(Board, Player) :- Board = [_,Player,_,_,Player,_,_,Player,_].
colwin(Board, Player) :- Board = [_,_,Player,_,_,Player,_,_,Player].

diagwin(Board, Player) :- Board = [Player,_,_,_,Player,_,_,_,Player].


diagwin(Board, Player) :- Board = [_,_,Player,_,Player,_,Player,_,_].

% Helping predicate for alternating play in a "self" game:

40
other(x,o).
other(o,x).

game(Board, Player) :- win(Board, Player), !, write([player, Player, wins]).


game(Board, Player) :-
other(Player,Otherplayer),
move(Board,Player,Newboard),!,
display(Newboard),
game(Newboard,Otherplayer).

move([b,B,C,D,E,F,G,H,I], Player, [Player,B,C,D,E,F,G,H,I]).


move([A,b,C,D,E,F,G,H,I], Player, [A,Player,C,D,E,F,G,H,I]).
move([A,B,b,D,E,F,G,H,I], Player, [A,B,Player,D,E,F,G,H,I]).
move([A,B,C,b,E,F,G,H,I], Player, [A,B,C,Player,E,F,G,H,I]).
move([A,B,C,D,b,F,G,H,I], Player, [A,B,C,D,Player,F,G,H,I]).
move([A,B,C,D,E,b,G,H,I], Player, [A,B,C,D,E,Player,G,H,I]).
move([A,B,C,D,E,F,b,H,I], Player, [A,B,C,D,E,F,Player,H,I]).
move([A,B,C,D,E,F,G,b,I], Player, [A,B,C,D,E,F,G,Player,I]).
move([A,B,C,D,E,F,G,H,b], Player, [A,B,C,D,E,F,G,H,Player]).

display([A,B,C,D,E,F,G,H,I]) :- write([A,B,C]),nl,write([D,E,F]),nl,
write([G,H,I]),nl,nl.

selfgame :- game([b,b,b,b,b,b,b,b,b],x).

% Predicates to support playing a game with the user:

x_can_win_in_one(Board) :- move(Board, x, Newboard), win(Newboard, x).

% The predicate orespond generates the computer's (playing o) reponse


% from the current Board.

orespond(Board,Newboard) :-
move(Board, o, Newboard),
win(Newboard, o), !.
orespond(Board,Newboard) :-
move(Board, o, Newboard),
not(x_can_win_in_one(Newboard)).
orespond(Board,Newboard) :-
move(Board, o, Newboard).
orespond(Board,Newboard) :-
not(member(b,Board)),!,
write('Cats game!'), nl,
Newboard = Board.
% The following translates from an integer description
% of x's move to a board transformation.
41
xmove([b,B,C,D,E,F,G,H,I], 1, [x,B,C,D,E,F,G,H,I]).
xmove([A,b,C,D,E,F,G,H,I], 2, [A,x,C,D,E,F,G,H,I]).
xmove([A,B,b,D,E,F,G,H,I], 3, [A,B,x,D,E,F,G,H,I]).
xmove([A,B,C,b,E,F,G,H,I], 4, [A,B,C,x,E,F,G,H,I]).
xmove([A,B,C,D,b,F,G,H,I], 5, [A,B,C,D,x,F,G,H,I]).
xmove([A,B,C,D,E,b,G,H,I], 6, [A,B,C,D,E,x,G,H,I]).
xmove([A,B,C,D,E,F,b,H,I], 7, [A,B,C,D,E,F,x,H,I]).
xmove([A,B,C,D,E,F,G,b,I], 8, [A,B,C,D,E,F,G,x,I]).
xmove([A,B,C,D,E,F,G,H,b], 9, [A,B,C,D,E,F,G,H,x]).
xmove(Board, _, Board) :- write('Illegal move.'), nl.

% The 0-place predicate playo starts a game with the user.

playo :- explain, playfrom([b,b,b,b,b,b,b,b,b]).

explain :-
write('You play X by entering integer positions followed by a period.'),nl,
display([1,2,3,4,5,6,7,8,9]).

playfrom(Board) :- win(Board, x), write('You win!').


playfrom(Board) :- win(Board, o), write('I win!').
playfrom(Board) :- read(N),
xmove(Board, N, Newboard),
display(Newboard),
orespond(Newboard, Newnewboard),
display(Newnewboard),
playfrom(Newnewboard).

42
PRACTICAL -12

AIM: Write a program for 8-queen problem.

Procedure:

STEP 1: Represent the board positions as 8*8 vector , i.e., [1,2,3,4,5,6,7,8]. Store the set of
queens in the list ‘Q’.
STEP 2: Calculate the permutation of the above eight numbers stored in set P. STEP 3: Let
the position where the first queen to be placed be (1,Y), for second be (2,Y1) and so on and
store the positions in Q.
STEP 4: Check for the safety of the queens through the predicate , ‘noattack ()’.
STEP 5: Calculate Y1-Y and Y-Y1. If both are not equal to Xdist , which is the X – distance
between the first queen and others, then go to Step 6 else go to Step 7.
STEP 6: Increment Xdist by 1.
STEP 7: Repeat above for the rest of the queens, until the end of the list is reached.
STEP 8: Print Q as answer.
STEP 9: Exit.

Code/Method:
PROGRAM
:- use_module(library(clpfd)).

% Main solution predicate


solution([]). % Base case: an empty list is a valid solution

solution([X/Y | Others]) :-
solution(Others), % Recursively check the rest of the queens
member(Y, [1,2,3,4,5,6,7,8]), % Ensure Y (the column) is between 1 and 8
noattack(X/Y, Others). % Ensure the current queen does not attack any
others

% No attack predicate (ensures queens don't attack each other)


noattack(_, []). % If there are no other queens, it's safe

noattack(X/Y, [X1/Y1 | Others]) :-


Y =\= Y1, % Ensure the queens are not in the same column
abs(Y - Y1) =\= abs(X - X1), % Ensure they are not on the same diagonal
noattack(X/Y, Others). % Continue checking for the rest

43
% Template for an 8-queen problem
template(T) :-
T = [1/Y1, 2/Y2, 3/Y3, 4/Y4, 5/Y5, 6/Y6, 7/Y7, 8/Y8],
Y1 in 1..8,
Y2 in 1..8,
Y3 in 1..8,
Y4 in 1..8,
Y5 in 1..8,
Y6 in 1..8,
Y7 in 1..8,
Y8 in 1..8.

44
Output:

45
PRACTICAL -13

AIM: Write a program to demonstrate family relationship.

Procedure:

A simple program to show family relationship. Provide some simple facts and make queries
on them.
Code/Method:
% Facts
parent(a, b). % a is a parent of b
parent(a, c). % a is a parent of c
parent(d, a). % d is a parent of a
parent(d, e). % d is a parent of e
male(a). % a is male
male(c). % c is male
female(b). % b is female
female(e). % e is female

% Rules
child(X, Y) :- parent(Y, X). % X is a child of Y if Y is the parent of
X

mother(X, Y) :- female(X), parent(X, Y). % X is the mother of Y if X is


female and X is a parent of Y

father(X, Y) :- male(X), parent(X, Y). % X is the father of Y if X is male


and X is a parent of Y

grandparent(X, Y) :- parent(X, Z), parent(Z, Y). % X is a grandparent of Y if


X is a parent of Z, and Z is a parent of Y

brother(X, Y) :- male(X), parent(V, X), parent(V, Y), X \= Y. % X is a


brother of Y if X is male, shares a parent with Y, and X is not the same as Y

sister(X, Y) :- female(X), parent(V, X), parent(V, Y), X \= Y. % X is a


sister of Y if X is female, shares a parent with Y, and X is not the same as Y

46
Output:

47
PRACTICAL -14

AIM: Write a program to show concept of list.

Code/Method:

% Define the predicate to handle lists of names


itnames([ram, kapil, shweta]).
itnames([ram, shweta, kapil]).

% Query to check the contents of the list:

48
Output:

49

You might also like