Ailabamit
Ailabamit
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
5
PRACTICAL -1
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
a) FACTS:
sister (sue,bill)
parent (ann.sam)
male(jo)
female(riya)
b) RULES:
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
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.
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:
8
Output:
9
PRACTICAL -2
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
Procedure:
Arithmetic
X is <arithmetic expression>
?- X is 2 + 2.
X=4
?- X is 3 * 4 + 2.
X = 14
?- X is 3 * (4 + 2).
X = 18
12
?- X is (8 / 4) / 2. X=1
X>Y
X<Y
X >= Y
X =< Y
?- 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:
13
Output:
14
PRACTICAL -4
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.
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
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:
% 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
19
Output:
20
PRACTICAL -6
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]]).
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)
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),
!.
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).
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,[]).
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
Procedure:
TheNQueensChessboard
Code/Method:
% Domain for queen
queen(q(Row, Col)).
% Example query:
% ?- nqueens(4), nl.
28
Output:
29
PRACTICAL -8
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 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
31
Output:
32
PRACTICAL -9
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: -
Code:
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).
35
Output:
36
PRACTICAL -10
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).
37
Output:
38
VALUE ADDED PROGRAMS
39
PRACTICAL -11
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:
40
other(x,o).
other(o,x).
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).
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.
explain :-
write('You play X by entering integer positions followed by a period.'),nl,
display([1,2,3,4,5,6,7,8,9]).
42
PRACTICAL -12
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)).
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
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
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
46
Output:
47
PRACTICAL -14
Code/Method:
48
Output:
49