AI Assignment PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Department of Computer Science & Engineering

RCC Institute of Information Technology, Kolkata


Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

W Laboratory Exercise
e
e
k
N
o
.
W Prolog Fundamentals
e Lab Experiments:
e 1. Write a Prolog program to find the sum of two numbers.
k
1 start:- sum,nl.
sum:- write('X= '),read(X),write('Y= '),read(Y),S is X+Y,write('Sum is '),write(S).

2 ?- start.
X= 26.
Y= |: 62.
Sum is 88
true.

2. Write a Prolog program to find whether a given number is odd or even.

odd_even(X):- X mod 2 =:= 0,


write('even number'),nl.
odd_even(X):- write('odd number'),nl.

6 ?- odd_even(19).
odd number
true.

7 ?- odd_even(16).
even number
true

3. What will be the output of following Prolog predicates –


 ?- X is 3+2. % expression on right side of  ?- Y is (3+2)*(4)-(1).
'is' X = 5.  ?- Y is -(*(+(3,2),4),1).
 ?- 3+2 is X. % expression on left side of 'is'  ?- X is 3*2, Y is X*2. X = 6, Y = 12.
ERROR: is/2: Arguments are not  ?- 3<5.
sufficiently instantiated  ?- 4<2.

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19


?- X = 3+2. %just instantiate variable X to  ?- 6>5.
value 3+2 X = 3+2. ?- 3+2 = X. X = 3+2.  ?- 12<=12.
 ?- X is +(3,2).  ?- 12 =< 7.
 ?- 5 is 3+2.  ?- 3+4 =< 7.
 ?- 3+2 is 5.  ?- 5=\=5. % 5 is not equal to 5.
 ?- X is 3*2.  ?- 5=\=4.
 ?- X is 3-2.  ?- 5=\=(3+2).
 ?- X is -(2,3).  ?- 8=8.
 ?- X is 5-3-1.  ?- 8=:=8. % 8 equal to 8.
 ?- X is -(5,3,1). %ERROR: is/2: Arithmetic:  ?- 8=:=9.
`(-)/3' is not a function  ?- (2+1)*10 = 30.
 ?- X is -(-(5,3),1).  ?- (2+1)*10 =:= 30.
 ?- X is 5-3-1. X = 1  ?- X=2, X<3.
 ?- X is 3/5. X = 0.6.  ?- X=4, X<3.
 ?- X is 3 mod 5.  ?- *(2,3) = 2*3.
 ?- X is 5 mod 3.  ?- X = Z.
 ?- X is 5^3.  ?-(X>3)=(4>3).
 ?- X is (5^3)^2.  ?- X = 3, C is X*X*X.
 ?- X = (5^3)^2.  ?- X = 3, X*X*X is C.
 ?- 25 is 5^2.  ?- is(Y,^(2,2)). % don't type space
 ?- Y is 3+2*4-1. between 'is' and bracket
W Prolog Fundamentals and Clauses
e Lab Experiments:
e 1. Write a Prolog program to find the maximum value among three values.
k 2. Write a Prolog program to find the factorial of a given number.
2
fact(0,1).
fact(X,Y):-X1 is X-1,fact(X1,Z),Y is X*Z.

5 ?- fact(6,X).
X = 720
3. Write a Prolog program to find the GCD and LCM of given two numbers.
gcd(X, Y, G) :- X = Y, G = X.
gcd(X, Y, G) :- X < Y, Y1 is Y-X,gcd2(X, Y1, G).
gcd(X, Y, G) :- X > Y, gcd(Y, X, G).
lcm(X,Y,LCM):-gcd2(X,Y,GCD), LCM is X*Y//GCD.

?- lcm(12,18,X).
X = 36 .

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

?- gcd(12,18,X).
X=6.

Lab Assignments:
1. Write a Prolog program to generate a Fibonacci series.
:- dynamic(stored/1).
memo(Goal) :-stored(Goal) -> true;
Goal, assertz(stored(Goal)).

fib(1,1) :- !, write('1, ').


fib(2,1) :- !, write('1, ').
fib(N,F) :-N1 is N-1,memo(fib(N1,F1)),N2 is N-2,memo(fib(N2,F2)),F is F1 + F2,write(F), write(',').

2 ?- fib(7,X).
1, 1, 2,3,5,8,13,
X = 13.

2. Write a Prolog program to solve the Tower of Hannoi Problem.


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).

[1] 14 ?- move(3,left,right,center).
Move top disk from left to right
Move top disk from left to center
Move top disk from right to center
Move top disk from left to right
Move top disk from center to left
Move top disk from center to right

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

Move top disk from left to right


true .

W Computation Problem in Prolog


e Lab Experiments:
e 1. Write a Prolog program to evaluate the XY, where X and Y are both integers.
k
3 power(0,N,0):- N>0.
power(X,0,1):- X>0.
power(X,N,V):-X>0,N>0,N1 is N-1,power(X,N1,V1), V is V1*X.

7 ?- power(2,3,R).
R=8.
2. Write a Prolog program to find the circumference and area of a circle.
start:- radius(R),circ(R,C),write('Circumference is '),write(C),nl,area(R,A),write('Area is ') ,write(A).
radius(R):- write('Radius= '),read(R).
circ(R,C):- C is 2*3.14*R.
area(R,A):- A is 3.14*R*R.

3 ?- start.
Radius= 1.
Circumference is 6.28
Area is 3.14
true.

3. Write a Prolog program to exchange of two values of two variables without using 3rd variable.

swapfirsttwo([X, Y | R], [Y, X | R]).

?-swapfirsttwo([4,13],X).
X=13,4.

Lab Assignments:
1. Write a Prolog program to find the nth Fibonacci number.
fib(0,0).
fib(1,1).
fib(X, Ans) :- Xm1 is X-1 ,Xm2 is X-2 ,fib(Xm1,Sub1), fib(Xm2,Sub2),Ans is Sub1+Sub2.

?- fib(6,X).
X=8.

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

W Using List in Prolog


e Lab Experiments:
e 1. Write a Prolog program to check whether the element is member of list or not.
k member(X,[X| ]).
4 member(X,[ |T]) :- member(X,T).

?- member(x,[w,x]).
true .

?- member(x,[]).
false.

2. Write a Prolog program to generate all integers in a given range.


range(I,I,[I]).
range(I,K,[I|L]) :- I < K, I1 is I + 1, range(I1,K,L).

?- range(10,50,L).
L = [10, 11, 12, 13, 14, 15, 16, 17, 18|...] .

3. Write a Prolog program to increment one value of list element.


inc([],[]).
inc([A|L],[A1|L1]):-A1 is A+1,inc(L,L1).

[1] 17 ?- inc([24,26,35,68,99],X).
X = [25, 27, 36, 69, 100].

4. Write a Prolog program to find the Kth element from a list.


nth(0,[X|_],X).
nth(N,[_|T],R):- M is N-1,nth(M,T,R).

[1] 12 ?- nth(2,[a,b,c,d],R).
R=c.
5. Write a Prolog program to find before and after list value of particular element in list.
?- conc(Before,[may|After],[jan,feb,mar,apr,may,june,july,aug,sep,oct,nov,dec]).
Before = [jan, feb, mar, apr],
After = [june, july, aug, sep, oct, nov, dec] .

?- conc([a,b],[c,d],[a,b,c,d]).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

true.

?- conc([a,b],[c,d],[a,b,a,c,d]).
false.

6. Write a Prolog program to generate all permutations of a list of elements.


takeout(X,[X|R],R).
takeout(X,[F|R],[F|S]) :- takeout(X,R,S).
perm([X|Y],Z) :- perm(Y,W), takeout(X,Z,W).
perm([],[]).

[1] 13 ?- perm([1,2,3],P).
P = [1, 2, 3] ;
P = [2, 1, 3] ;
P = [2, 3, 1] ;
P = [1, 3, 2] ;
P = [3, 1, 2] ;
P = [3, 2, 1] ;
False.
Lab Assignments:
1. Write a Prolog program to decompose a list.
writeall([]).
writeall([A|L]):- write(A),nl,writeall(L).

[1] 15 ?- writeall([alpha,'Thi is string',20,[a,b,c]]).


alpha
Thi is string
20
[a,b,c]
true.
2. Write a Prolog program to determine whether a given list is palindrome or not.
palindrome(A):-reverse(A,A).

?- palindrome([a,b,c,b,a]).
true.
?- palindrome([a,b,c,b,e]).
false.

W String and Graph Problem in Prolog


e Lab Experiments:

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

e 1. Write a Prolog program to Join two string or three string.


k join2(String1,String2,Newstring):-
5 name(String1,L1),name(String2,L2),append(L1,L2,Newlist),name(Newstring,Newlist).
join3(String1,String2,String3,Newstring):-join2(String1,String2,S),join2(S,String3,Newstring).

?- join2('Souvik',' Majumdar',S).
S = 'Souvik Majumdar'.

?- join3('This is',' an',' example',Newstring).


Newstring = 'This is an example'.

2. Write a Prolog program to count the number of vowels in a list of characters (word).
vowel(X):- member(X,[a,e,i,o,u]).
nr_vowel([],0).
nr_vowel([X|T],N):- vowel(X),nr_vowel(T,N1),N is N1+1,!.
nr_vowel([X|T],N):- nr_vowel(T,N).

[1] 8 ?- nr_vowel([a,r,e,d,i],X).
X = 3.

3. Write a Prolog program to find whether the node of the following graph is connected or not.

edge(1,2).
edge(1,4).
edge(1,3).
edge(2,3).
edge(2,5).
edge(3,4).
edge(3,5).
edge(4,5).
connected(X,Y) :- edge(X,Y) ; edge(Y,X).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

Or

connected(X,Y) :- edge(X,Y).
connected(X,Y) :- edge(Y,X).

Lab Assignments:
1. Write a Prolog program to find the last element of a list.
last([X],X).
last([H|T],R):- last(T,R).

?- last([a],R)
R=a
?-last([a,b,1,c],X).
X=c
?-last([a,b,[c,[d]]],X).
X=[c,[d]]

2. Write a Prolog program to find the size of a list.


my_length([],0).
my_length([_|T],R):- my_length(T,R1),R is R1+1.

?- my_length([a,b,[c,d],e],R).
R=4
?- my_length([[],[]],R).
R=2
?- my_length([[[]]],R).
R=1

W Elements Sorting in Prolog


e Lab Experiments:
e 1. Write a Prolog program to sort a given list using bubble sort.
k
6 bubble_sort(List,Sorted):-b_sort(List,[],Sorted).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

b_sort([],Acc,Acc).
b_sort([H|T],Acc,Sorted):-bubble(H,T,NT,Max),b_sort(NT,[Max|Acc],Sorted).

bubble(X,[],[],X).
bubble(X,[Y|T],[Y|NT],Max):-X>Y,bubble(X,T,NT,Max).
bubble(X,[Y|T],[X|NT],Max):-X=<Y,bubble(Y,T,NT,Max).

[1] 11 ?- bubble_sort([25,3,65,1,12],A).
A = [1, 3, 12, 25, 65] .

2. Write a Prolog program to sort a given list using insertion sort.

insert_sort(List,Sorted):-i_sort(List,[],Sorted).
i_sort([],Acc,Acc).
i_sort([H|T],Acc,Sorted):-insert(H,Acc,NAcc),i_sort(T,NAcc,Sorted).

insert(X,[Y|T],[Y|NT]):-X>Y,insert(X,T,NT).
insert(X,[Y|T],[X,Y|T]):-X=<Y.
insert(X,[],[X]).

[1] 10 ?- insert_sort([25,3,65,1,12],A).
A = [1, 3, 12, 25, 65] .

3. Write a Prolog program to sort a given list using merge sort.

merge(A,[],A).
merge([],B,B).
merge([A|Ra],[B|Rb],[A|M]) :- A =< B, merge(Ra,[B|Rb],M).
merge([A|Ra],[B|Rb],[B|M]) :- A > B, merge([A|Ra],Rb,M).
mergesort([],[]). /* covers special case */
mergesort([A],[A]).
mergesort([A,B|R],S) :-split([A,B|R],L1,L2),mergesort(L1,S1), mergesort(L2,S2),merge(S1,S2,S).

split([],[],[]).
split([A],[A],[]).
split([A,B|R],[A|Ra],[B|Rb]) :- split(R,Ra,Rb).

[1] 9 ?- mergesort([4,3,6,5,9,1,7],S).
S = [1, 3, 4, 5, 6, 7, 9] .

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

Lab Assignments:
1. Write a Prolog program to sort a given list using quick sort.
/* [+,-] */
quicksort([], []).
quicksort([HEAD | TAIL], SORTED) :- partition(HEAD, TAIL, LEFT, RIGHT),
quicksort(LEFT, SORTEDL),
quicksort(RIGHT, SORTEDR),
append(SORTEDL, [HEAD | SORTEDR], SORTED).

/* [+,+,-,-] */
partition(PIVOT, [], [], []).
partition(PIVOT, [HEAD | TAIL], [HEAD | LEFT], RIGHT) :- HEAD @=< PIVOT,
partition(PIVOT, TAIL, LEFT, RIGHT).
partition(PIVOT, [HEAD | TAIL], LEFT, [HEAD | RIGHT]) :- HEAD @> PIVOT,
partition(PIVOT, TAIL, LEFT, RIGHT).

/* [+,+,-] */
append([], LIST, LIST).
append([HEAD | LIST1], LIST2, [HEAD | LIST3]) :- append(LIST1, LIST2, LIST3).

3 ?- quicksort([25,3,4,9],X).
X = [3, 4, 9, 25] .

2. Write a Prolog program to implement the binary search.

%checks to see if a value is contained in a list of integers,


%using binary search tactics

%success base case


%A list contains a value if its center is the value
contains(List, Value):- even_division(_, [Value|_], List).
%case that Value is large
%A list contains a value if the value is larger than the center,
%and the second half of the list contains the value
contains(List, Value):- even_division(_, [Center|SecondHalf], List),
Center<Value, SecondHalf \= [],
contains(SecondHalf, Value).
%case that Value is small

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

%A list contains a value if the value is smaller than the center,


%and the first half of the list contains the value
contains(List, Value):- even_division(FirstHalf, [Center|_], List),
Center>Value, FirstHalf\=[],
contains(FirstHalf, Value).
%even_division(First, Second, Xs) is true when
% Xs is the concatenation of First and Second,
% and First and Second are either the same length
% or Second is one element longer than first.
even_division(First, Second, Xs) :- append(First, Second, Xs),
length(First,F), length(Second,S),
S>=F, S-F=<1.

6 ?- contains([56,8,90,98],98).
true .

7 ?- contains([56,8,90,98],9).
false.
W Tree family in Prolog
e Lab Experiments:
e 1. Write a Prolog program for below tree data relation.
k
7

i. Create a tree database


ii. X and Y are siblings
iii. X and Y are on the same level in the tree.
iv. Depth of node in the tree.
v. Locate node by finding a path from root down to the node.
vi. Calculate the height of a node, length of longest path to

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

vii. A leaf under the node

/* The tree database */

:- op(500,xfx,'is_parent').

a is_parent b. c is_parent g. f is_parent l. j is_parent q.


a is_parent c. c is_parent h. f is_parent m. j is_parent r.
a is_parent d. c is_parent i. h is_parent n. j is_parent s.
b is_parent e. d is_parent j. i is_parent o. m is_parent t.
b is_parent f. e is_parent k. i is_parent p.

/* X and Y are siblings */

:- op(500,xfx,'is_sibling_of').

X is_sibling_of Y :- Z is_parent X,
Z is_parent Y,
X \== Y.

/* X and Y are on the same level in the tree. */

:-op(500,xfx,'is_same_level_as').

X is_same_level_as X .
X is_same_level_as Y :- W is_parent X,
Z is_parent Y,
W is_same_level_as Z.

/* Depth of node in the tree. */

:- op(500,xfx,'has_depth').

a has_depth 0 :- !.
Node has_depth D :- Mother is_parent Node,
Mother has_depth D1,
D is D1 + 1.

/* Locate node by finding a path from root down to the node. */


locate(Node) :- path(Node),
write(Node),

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

nl.
path(a). /* Can start at a. */
path(Node) :- Mother is_parent Node, /* Choose parent, */
path(Mother), /* find path and then */
write(Mother),
write(' --> ').

/* Calculate the height of a node, length of longest path to


a leaf under the node. */

height(N,H) :- setof(Z,ht(N,Z),Set), max(Set,0,H).

ht(Node,0) :- leaf(Node), !.
ht(Node,H) :- Node is_parent Child,
ht(Child,H1),
H is H1 +1.

leaf(Node) :- not(is_parent(Node,Child)). %/* Node grounded */

max([],M,M).
max([X|R],M,A) :- (X > M -> max(R,X,A) ; max(R,M,A)).

?- h is_sibling_of S.
S=g ;
S=i ;
no

?- t has_depth D.
D=4

?- locate(n).
a --> c --> h --> n

2. Write a Prolog program to represent a family tree and write the predicates for different
relationships like father, mother, brother, sister, cousin, grandmother, grandfather etc.
i. Create a family database
ii. Display Father of?
iii. Display Mother of?
iv. List all brothers of?
v. List all sisters of?

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

vi. List all grandson of?


vii. List all granddaughter of?
viii. List all uncles of?
ix. List all aunty of?
x. List all cousins of?
3. Write a Prolog program to verify if three numbers can be the edges of a triangle.

start:- write('input a= '),read(A),


write('input b= '),read(B),
write('input c= '),read(C),
A >= 0,B >= 0,C >= 0, /* must be positive */
A < B+C,B < C+A,C < A+B,
write('These numbers are the edges of a triangle.').

?- start.
input a= 3.
input b= 4.
input c= 5.
These numbers are the edges of a triangle.
yes

Lab Assignments:
1. A binary tree can be defined in terms of 2 predicates:
emptyBT, the empty binary tree.
a. BTTree(N,T1,T2) that is true if N is the root of a binary tree with left subtree T1 and right
subtree T2, where all the items in T1 are less than or equal to N and all the items in T2 are
greater than N.
b. Write a Prolog program that implements the following predicates:
i. insert(I,T1,T2) is true if T2 is the binary tree resulting from I being inserted into binary
tree T1.
ii. preorder(T,L) is true if L is a list of nodes generated by a preorder traversal of the binary
tree T.
iii. inorder(T,L) is true if L is a list of nodes generated by a inorder traversal of the binary tree
T.
iv. postorder(T,L) is true if L is a list of nodes generated by a postorder traversal of the binary
tree T.
v. search(T,I) is true if I is contained in the binary tree T.
vi. height(T,H) is true if H is the height of the binary tree T. An empty tree has height 0 and a
tree with one item has height 1.
W AI Searching Based Problems Using Prolog

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

e Lab Experiments:
e 1. Write a Prolog program for Map colourings of following figure.
k
8

2. Write a Prolog program to solve the Chess queens challenge puzzle problem.
3. Write a program of the A* algorithm in Prolog

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%
%%%
%%% A* Algorithm
%%%
%%%
%%% Nodes have form S#D#F#A
%%% where S describes the state or configuration
%%% D is the depth of the node
%%% F is the evaluation function value
%%% A is the ancestor list for the node

:- op(400,yfx,'#'). /* Node builder notation */

solve(State,Soln) :- f_function(State,0,F),
search([State#0#F#[]],S), reverse(S,Soln).

f_function(State,D,F) :- h_function(State,H),
F is D + H.

search([State#_#_#Soln|_], Soln) :- goal(State).


search([B|R],S) :- expand(B,Children),
insert_all(Children,R,Open),
search(Open,S).

insert_all([F|R],Open1,Open3) :- insert(F,Open1,Open2),
insert_all(R,Open2,Open3).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

insert_all([],Open,Open).

insert(B,Open,Open) :- repeat_node(B,Open), ! .
insert(B,[C|R],[B,C|R]) :- cheaper(B,C), ! .
insert(B,[B1|R],[B1|S]) :- insert(B,R,S), !.
insert(B,[],[B]).

repeat_node(P#_#_#_, [P#_#_#_|_]).

cheaper( _#_#F1#_ , _#_#F2#_ ) :- F1 < F2.

expand(State#D#_#S,All_My_Children) :-
bagof(Child#D1#F#[Move|S],
(D1 is D+1,
move(State,Child,Move),
f_function(Child,D1,F)),
All_My_Children).
Lab Assignments :
1. Write a Prolog program to solve the 8-puzzle problem.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%
%%%
%%% A* Algorithm
%%%
%%%
%%% Nodes have form S#D#F#A
%%% where S describes the state or configuration
%%% D is the depth of the node
%%% F is the evaluation function value
%%% A is the ancestor list for the node

:- op(400,yfx,'#'). /* Node builder notation */

solve(State,Soln) :- f_function(State,0,F),
search([State#0#F#[]],S), reverse(S,Soln).

f_function(State,D,F) :- h_function(State,H),
F is D + H.

search([State#_#_#Soln|_], Soln) :- goal(State).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

search([B|R],S) :- expand(B,Children),
insert_all(Children,R,Open),
search(Open,S).

insert_all([F|R],Open1,Open3) :- insert(F,Open1,Open2),
insert_all(R,Open2,Open3).
insert_all([],Open,Open).

insert(B,Open,Open) :- repeat_node(B,Open), ! .
insert(B,[C|R],[B,C|R]) :- cheaper(B,C), ! .
insert(B,[B1|R],[B1|S]) :- insert(B,R,S), !.
insert(B,[],[B]).

repeat_node(P#_#_#_, [P#_#_#_|_]).

cheaper( _#_#F1#_ , _#_#F2#_ ) :- F1 < F2.

expand(State#D#_#S,All_My_Children) :-
bagof(Child#D1#F#[Move|S],
(D1 is D+1,
move(State,Child,Move),
f_function(Child,D1,F)),
All_My_Children).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%
%%%
%%% 8-puzzle solver
%%%
%%%
%%% State have form A/B/C/D/E/F/G/H/I
%%% where {A,...,I} = {0,...,8}
%%% 0 represents the empty tile
%%%

goal(1/2/3/8/0/4/7/6/5).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

%%% The puzzle moves

left( A/0/C/D/E/F/H/I/J , 0/A/C/D/E/F/H/I/J ).


left( A/B/C/D/0/F/H/I/J , A/B/C/0/D/F/H/I/J ).
left( A/B/C/D/E/F/H/0/J , A/B/C/D/E/F/0/H/J ).
left( A/B/0/D/E/F/H/I/J , A/0/B/D/E/F/H/I/J ).
left( A/B/C/D/E/0/H/I/J , A/B/C/D/0/E/H/I/J ).
left( A/B/C/D/E/F/H/I/0 , A/B/C/D/E/F/H/0/I ).

up( A/B/C/0/E/F/H/I/J , 0/B/C/A/E/F/H/I/J ).


up( A/B/C/D/0/F/H/I/J , A/0/C/D/B/F/H/I/J ).
up( A/B/C/D/E/0/H/I/J , A/B/0/D/E/C/H/I/J ).
up( A/B/C/D/E/F/0/I/J , A/B/C/0/E/F/D/I/J ).
up( A/B/C/D/E/F/H/0/J , A/B/C/D/0/F/H/E/J ).
up( A/B/C/D/E/F/H/I/0 , A/B/C/D/E/0/H/I/F ).

right( A/0/C/D/E/F/H/I/J , A/C/0/D/E/F/H/I/J ).


right( A/B/C/D/0/F/H/I/J , A/B/C/D/F/0/H/I/J ).
right( A/B/C/D/E/F/H/0/J , A/B/C/D/E/F/H/J/0 ).
right( 0/B/C/D/E/F/H/I/J , B/0/C/D/E/F/H/I/J ).
right( A/B/C/0/E/F/H/I/J , A/B/C/E/0/F/H/I/J ).
right( A/B/C/D/E/F/0/I/J , A/B/C/D/E/F/I/0/J ).

down( A/B/C/0/E/F/H/I/J , A/B/C/H/E/F/0/I/J ).


down( A/B/C/D/0/F/H/I/J , A/B/C/D/I/F/H/0/J ).
down( A/B/C/D/E/0/H/I/J , A/B/C/D/E/J/H/I/0 ).
down( 0/B/C/D/E/F/H/I/J , D/B/C/0/E/F/H/I/J ).
down( A/0/C/D/E/F/H/I/J , A/E/C/D/0/F/H/I/J ).
down( A/B/0/D/E/F/H/I/J , A/B/F/D/E/0/H/I/J ).

%%% the heuristic function


h_function(Puzz,H) :- p_fcn(Puzz,P),
s_fcn(Puzz,S),
H is P + 3*S.

%%% the move


move(P,C,left) :- left(P,C).
move(P,C,up) :- up(P,C).
move(P,C,right) :- right(P,C).
move(P,C,down) :- down(P,C).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

%%% the Manhattan distance function


p_fcn(A/B/C/D/E/F/G/H/I, P) :-
a(A,Pa), b(B,Pb), c(C,Pc),
d(D,Pd), e(E,Pe), f(F,Pf),
g(G,Pg), h(H,Ph), i(I,Pi),
P is Pa+Pb+Pc+Pd+Pe+Pf+Pg+Ph+Pg+Pi.

a(0,0). a(1,0). a(2,1). a(3,2). a(4,3). a(5,4). a(6,3). a(7,2). a(8,1).


b(0,0). b(1,1). b(2,0). b(3,1). b(4,2). b(5,3). b(6,2). b(7,3). b(8,2).
c(0,0). c(1,2). c(2,1). c(3,0). c(4,1). c(5,2). c(6,3). c(7,4). c(8,3).
d(0,0). d(1,1). d(2,2). d(3,3). d(4,2). d(5,3). d(6,2). d(7,2). d(8,0).
e(0,0). e(1,2). e(2,1). e(3,2). e(4,1). e(5,2). e(6,1). e(7,2). e(8,1).
f(0,0). f(1,3). f(2,2). f(3,1). f(4,0). f(5,1). f(6,2). f(7,3). f(8,2).
g(0,0). g(1,2). g(2,3). g(3,4). g(4,3). g(5,2). g(6,2). g(7,0). g(8,1).
h(0,0). h(1,3). h(2,3). h(3,3). h(4,2). h(5,1). h(6,0). h(7,1). h(8,2).
i(0,0). i(1,4). i(2,3). i(3,2). i(4,1). i(5,0). i(6,1). i(7,2). i(8,3).

%%% the out-of-cycle function


s_fcn(A/B/C/D/E/F/G/H/I, S) :-
s_aux(A,B,S1), s_aux(B,C,S2), s_aux(C,F,S3),
s_aux(F,I,S4), s_aux(I,H,S5), s_aux(H,G,S6),
s_aux(G,D,S7), s_aux(D,A,S8), s_aux(E,S9),
S is S1+S2+S3+S4+S5+S6+S7+S8+S9.

s_aux(0,0) :- !.
s_aux(_,1).

s_aux(X,Y,0) :- Y is X+1, !.
s_aux(8,1,0) :- !.
s_aux(_,_,2).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%
%%%
%%% 8-puzzle animation -- using VT100 character graphics
%%%
%%%
%%%

puzzle(P) :- solve(P,S),

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

animate(P,S),
message.

animate(P,S) :- initialize(P),
cursor(1,2), write(S),
cursor(1,22), write('Hit ENTER to step solver.'),
get0(_X),
play_back(S).

:- dynamic location/3. %%% So that location of a tile


%%% can be retracted/asserted.
%%% Location(s) asserted and retracted
%%% by puzzle animator below

initialize(A/B/C/D/E/F/H/I/J) :-
cls,
retractall(location(_,_,_)),
assert(location(A,20,5)),
assert(location(B,30,5)),
assert(location(C,40,5)),
assert(location(F,40,10)),
assert(location(J,40,15)),
assert(location(I,30,15)),
assert(location(H,20,15)),
assert(location(D,20,10)),
assert(location(E,30,10)), draw_all.

draw_all :- draw(1), draw(2), draw(3), draw(4),


draw(5), draw(6), draw(7), draw(8).

%%% play_back([left,right,up,...]).
play_back([M|R]) :- call(M), get0(_X), play_back(R).
play_back([]) :- cursor(1,24). %%% Put cursor out of the way

message :- nl,nl,
write(' ********************************************'), nl,
write(' * Enter 8-puzzle goals in the form ... *'), nl,
write(' * ?- puzzle(0/8/1/2/4/3/7/6/5). *'), nl,
write(' * Enter goal ''message'' to reread this. *'), nl,
write(' ********************************************'), nl, nl.

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

cursor(X,Y) :- put(27), put(91), %%% ESC [


write(Y),
put(59), %%% ;
write(X),
put(72). %%% M

%%% clear the screen, quickly


cls :- put(27), put("["), put("2"), put("J").

%%% video attributes -- bold and blink not working


plain :- put(27), put("["), put("0"), put("m").
reverse_video :- put(27), put("["), put("7"), put("m").

%%% Tile objects, character map(s)


%%% Each tile should be drawn using the character map,
%%% drawn at 'location', which is asserted and retracted
%%% by 'playback'.
character_map(N, [ [' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ', N ,' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' '] ]).

%%% move empty tile (spot) to the left


left :- retract(location(0,X0,Y0)),
Xnew is X0 - 10,
location(Tile,Xnew,Y0),
assert(location(0,Xnew,Y0)),
right(Tile),right(Tile),right(Tile),
right(Tile),right(Tile),
right(Tile),right(Tile),right(Tile),
right(Tile),right(Tile).

up :- retract(location(0,X0,Y0)),
Ynew is Y0 - 5,
location(Tile,X0,Ynew),
assert(location(0,X0,Ynew)),
down(Tile),down(Tile),down(Tile),down(Tile),down(Tile).

right :- retract(location(0,X0,Y0)),

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

Xnew is X0 + 10,
location(Tile,Xnew,Y0),
assert(location(0,Xnew,Y0)),
left(Tile),left(Tile),left(Tile),left(Tile),left(Tile),
left(Tile),left(Tile),left(Tile),left(Tile),left(Tile).

down :- retract(location(0,X0,Y0)),
Ynew is Y0 + 5,
location(Tile,X0,Ynew),
assert(location(0,X0,Ynew)),
up(Tile),up(Tile),up(Tile),up(Tile),up(Tile).

draw(Obj) :- reverse_video, character_map(Obj,M),


location(Obj,X,Y),
draw(X,Y,M), plain.

%%% hide tile


hide(Obj) :- character_map(Obj,M),
location(Obj,X,Y),
hide(X,Y,M).

hide(_,_,[]).
hide(X,Y,[R|G]) :- hide_row(X,Y,R),
Y1 is Y + 1,
hide(X,Y1,G).

hide_row(_,_,[]).
hide_row(X,Y,[_|R]) :- cursor(X,Y),
write(' '),
X1 is X + 1,
hide_row(X1,Y,R).

%%% draw tile


draw(_,_,[]).
draw(X,Y,[R|G]) :- draw_row(X,Y,R),
Y1 is Y + 1,
draw(X,Y1,G).

draw_row(_,_,[]).
draw_row(X,Y,[P|R]) :- cursor(X,Y),

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

write(P),
X1 is X + 1,
draw_row(X1,Y,R).

%%% Move an Object up


up(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
Y1 is Y - 1,
assert(location(Obj,X,Y1)),
draw(Obj).

down(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
Y1 is Y + 1,
assert(location(Obj,X,Y1)),
draw(Obj).

left(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
X1 is X - 1,
assert(location(Obj,X1,Y)),
draw(Obj).

right(Obj) :- hide(Obj),
retract(location(Obj,X,Y)),
X1 is X + 1,
assert(location(Obj,X1,Y)),
draw(Obj).

:- message.
2. Write a Prolog program to solve the 8-Queen problem
%% To use, load in interpreter and call
%%
%% ?- queensSolution(A).
%%
%% To get all solutions at once, call
%%
%% ?- setof(A,queensSolution(A),B).
%%

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

%% Board representation is a list with each element representing a queen on a


%% separate file (left to right) with the integer representing the rank the
%% queen is located on.
%%
%% This program uses the traditional brute force method, first solving the
%% Eight rooks problem and then eliminating solutions in which there is
%% diagonal contact.

queensSolution(A) :-queens(A), \+ diagonalContact(A).

rank(1).
rank(2).
rank(3).
rank(4).
rank(5).
rank(6).
rank(7).
rank(8).

queens([A,B,C,D,E,F,G,H]) :-queens__([A,B,C,D,E,F,G,H]),queens_([A,B,C,D,E,F,G,H]).

queens__([A]) :- rank(A).

queens__([A|B]) :-rank(A),queens__(B).

queens_([_]).

queens_([A|B]) :- \+ member(A,B),queens_(B).

diagonalContact([A|B]) :-diagonalContact_(A,1,B); diagonalContact(B).

diagonalContact_(A,B,[C|D]) :-A+B =:= C; A-B =:= C;( E is B+1,diagonalContact_(A,E,D)).

?- setof(A,queensSolution(A),B), length(B,C).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

B=
[[1,5,8,6,3,7,2,4],[1,6,8,3,7,4,2,5],[1,7,4,6,8,2,5,3],[1,7,5,8,2,4,6,3],[2,4,6,8,3,1,7,5],[2,5,7,1,3,8,6,4],[2,5,7,4,1,8,6,
3],[2,6,1,7,4,8,3,5],[2,6,8,3,1,4,7,5],[2,7,3,6,8,5,1,4],[2,7,5,8,1,4,6,3],[2,8,6,1,3,5,7,4],[3,1,7,5,8,2,4,6],[3,5,2,8,1,7,
4,6],[3,5,2,8,6,4,7,1],[3,5,7,1,4,2,8,6],[3,5,8,4,1,7,2,6],[3,6,2,5,8,1,7,4],[3,6,2,7,1,4,8,5],[3,6,2,7,5,1,8,4],[3,6,4,1,8,
5,7,2],[3,6,4,2,8,5,7,1],[3,6,8,1,4,7,5,2],[3,6,8,1,5,7,2,4],[3,6,8,2,4,1,7,5],[3,7,2,8,5,1,4,6],[3,7,2,8,6,4,1,5],[3,8,4,7,
1,6,2,5],[4,1,5,8,2,7,3,6],[4,1,5,8,6,3,7,2],[4,2,5,8,6,1,3,7],[4,2,7,3,6,8,1,5],[4,2,7,3,6,8,5,1],[4,2,7,5,1,8,6,3],[4,2,8,
5,7,1,3,6],[4,2,8,6,1,3,5,7],[4,6,1,5,2,8,3,7],[4,6,8,2,7,1,3,5],[4,6,8,3,1,7,5,2],[4,7,1,8,5,2,6,3],[4,7,3,8,2,5,1,6],[4,7,
5,2,6,1,3,8],[4,7,5,3,1,6,8,2],[4,8,1,3,6,2,7,5],[4,8,1,5,7,2,6,3],[4,8,5,3,1,7,2,6],[5,1,4,6,8,2,7,3],[5,1,8,4,2,7,3,6],[5,
1,8,6,3,7,2,4],[5,2,4,6,8,3,1,7],[5,2,4,7,3,8,6,1],[5,2,6,1,7,4,8,3],[5,2,8,1,4,7,3,6],[5,3,1,6,8,2,4,7],[5,3,1,7,2,8,6,4],[
5,3,8,4,7,1,6,2],[5,7,1,3,8,6,4,2],[5,7,1,4,2,8,6,3],[5,7,2,4,8,1,3,6],[5,7,2,6,3,1,4,8],[5,7,2,6,3,1,8,4],[5,7,4,1,3,8,6,2]
,[5,8,4,1,3,6,2,7],[5,8,4,1,7,2,6,3],[6,1,5,2,8,3,7,4],[6,2,7,1,3,5,8,4],[6,2,7,1,4,8,5,3],[6,3,1,7,5,8,2,4],[6,3,1,8,4,2,7,
5],[6,3,1,8,5,2,4,7],[6,3,5,7,1,4,2,8],[6,3,5,8,1,4,2,7],[6,3,7,2,4,8,1,5],[6,3,7,2,8,5,1,4],[6,3,7,4,1,8,2,5],[6,4,1,5,8,2,
7,3],[6,4,2,8,5,7,1,3],[6,4,7,1,3,5,2,8],[6,4,7,1,8,2,5,3],[6,8,2,4,1,7,5,3],[7,1,3,8,6,4,2,5],[7,2,4,1,8,5,3,6],[7,2,6,3,1,
4,8,5],[7,3,1,6,8,5,2,4],[7,3,8,2,5,1,6,4],[7,4,2,5,8,1,3,6],[7,4,2,8,6,1,3,5],[7,5,3,1,6,8,2,4],[8,2,4,1,7,5,3,6],[8,2,5,3,
1,7,4,6],[8,3,1,6,2,5,7,4],[8,4,1,3,6,2,7,5]]
C = 92
W Search Space roblems in Prolog
e Lab Experiments :
e 1. Write a Prolog program to solve the αβ search for tic-tac-toe game in Prolog.
k
9
:- set_prolog_flag(toplevel_print_options,

[quoted(true), portray(true), max_depth(0)]).

:- use_module(minimax).

% bestMove(+Pos, -NextPos)

% Compute the best Next Position from Position Pos

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

% with minimax or alpha-beta algorithm.

bestMove(Pos, NextPos) :-

minimax(Pos, NextPos, _).

% We represent a game position by a list [Player, State, Board],

% where Player is the next player to play,

% State is equal to 'play' if not final posit., 'win' if win or 'draw' if draw

% and Board is the actual board of the game.

% The board is represented by a list of 9 elements

% (the first 3 elements are the first line of the board, ...).

% An empty case is represented by '0'.

% We choose x to be the MAX player and o the MIN player.

% TODO :

% - Add the number of empty cases in Board to test draw faster.

% - Try to not test all lines/cols/diags for winning or draw after a move,

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

% but only the modified ones.

% play

% Start the game.

play :-

nl,

write('********************'), nl,

write('* Prolog TicTacToe *'), nl,

write('********************'), nl, nl,

write('Rem : x starts the game'), nl,

playAskColor.

% playAskColor

% Ask the color for the human player and start the game with it.

playAskColor :-

nl, write('Color for human player ? (x or o)'), nl,

read(Player), nl,

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

Player \= o, Player \= x, !, % If not x or o -> not a valid color

write('Error : not a valid color !'), nl,

playAskColor % Ask again

EmptyBoard = [0, 0, 0, 0, 0, 0, 0, 0, 0],

show(EmptyBoard), nl,

% Start the game with color and emptyBoard

play([x, play, EmptyBoard], Player)

).

% play(+Position, +HumanPlayer)

% If next player to play in position is equal to HumanPlayer -> Human must play

% Ask to human what to do.

play([Player, play, Board], Player) :- !,

nl, write('Next move ?'), nl,

read(Pos), nl, % Ask human where to play

humanMove([Player, play, Board], [NextPlayer, State, NextBoard], Pos), !,

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

show(NextBoard),

State = win, !, % If Player win -> stop

nl, write('End of game : '),

write(Player), write(' win !'), nl, nl

State = draw, !, % If draw -> stop

nl, write('End of game : '),

write(' draw !'), nl, nl

play([NextPlayer, play, NextBoard], Player) % Else -> continue the game

write('-> Bad Move !'), nl, % If humanMove fail -> bad move

play([Player, play, Board], Player) % Ask again

).

% play(+Position, +HumanPlayer)

% If it is not human who must play -> Computer must play

% Compute the best move for computer with minimax or alpha-beta.

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

play([Player, play, Board], HumanPlayer) :-

nl, write('Computer play : '), nl, nl,

% Compute the best move

bestMove([Player, play, Board], [NextPlayer, State, BestSuccBoard]),

show(BestSuccBoard),

State = win, !, % If Player win -> stop

nl, write('End of game : '),

write(Player), write(' win !'), nl, nl

State = draw, !, % If draw -> stop

nl, write('End of game : '), write(' draw !'), nl, nl

% Else -> continue the game

play([NextPlayer, play, BestSuccBoard], HumanPlayer)

).

% nextPlayer(X1, X2)

% True if X2 is the next player to play after X1.

nextPlayer(o, x).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

nextPlayer(x, o).

% move(+Pos, -NextPos)

% True if there is a legal (according to rules) move from Pos to NextPos.

move([X1, play, Board], [X2, State, NextBoard]) :-

nextPlayer(X1, X2),

move_aux(X1, Board, NextBoard),

winningPos(X1, NextBoard), !, State = win ;

drawPos(NextBoard), !, State = draw ;

State = play

).

% move_aux(+Player, +Board, -NextBoard)

% True if NextBoard is Board whith an empty case replaced by Player mark.

move_aux(P, [0|Bs], [P|Bs]).

move_aux(P, [B|Bs], [B|B2s]) :-

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

move_aux(P, Bs, B2s).

% min_to_move(+Pos)

% True if the next player to play is the MIN player.

min_to_move([o, _, _]).

% max_to_move(+Pos)

% True if the next player to play is the MAX player.

max_to_move([x, _, _]).

% When human play

humanMove([X1, play, Board], [X2, State, NextBoard], Pos) :-

nextPlayer(X1, X2),

set1(Pos, X1, Board, NextBoard),

winningPos(X1, NextBoard), !, State = win ;

drawPos(NextBoard), !, State = draw ;

State = play

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

).

% set1(+Elem, +Pos, +List, -ResList).

% Set Elem at Position Pos in List => Result in ResList.

% Rem : counting starts at 1.

set1(1, E, [X|Ls], [E|Ls]) :- !, X = 0.

set1(P, E, [X|Ls], [X|L2s]) :-

number(P),

P1 is P - 1,

set1(P1, E, Ls, L2s).

% evalPos(+Pos, -Val) :-

% True if Val the the result of the evaluation function at Pos.

% We will only evaluate for final position.

% So we will only have MAX win, MIN win or draw.

% We will use 1 when MAX win

% -1 when MIN win

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

% 0 otherwise.

evalPos([o, win, _], 1). % Previous player (MAX) has win.

evalPos([x, win, _], -1). % Previous player (MIN) has win.

evalPos([_, draw, _], 0).

% winningPos(+Player, +Board)

% True if Player win in Board.

winningPos(P, [X1, X2, X3, X4, X5, X6, X7, X8, X9]) :-

equal(X1, X2, X3, P) ; % 1st line

equal(X4, X5, X6, P) ; % 2nd line

equal(X7, X8, X9, P) ; % 3rd line

equal(X1, X4, X7, P) ; % 1st col

equal(X2, X5, X8, P) ; % 2nd col

equal(X3, X6, X9, P) ; % 3rd col

equal(X1, X5, X9, P) ; % 1st diag

equal(X3, X5, X7, P). % 2nd diag

% equal(+W, +X, +Y, +Z).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

% True if W = X = Y = Z.

equal(X, X, X, X).

% drawPos(+Player, +Board)

% True if the game is a draw.

drawPos(Board) :-

\+ member(0, Board).

% show(+Board)

% Show the board to current output.

show([X1, X2, X3, X4, X5, X6, X7, X8, X9]) :-

write(' '), show2(X1),

write(' | '), show2(X2),

write(' | '), show2(X3), nl,

write(' -----------'), nl,

write(' '), show2(X4),

write(' | '), show2(X5),

write(' | '), show2(X6), nl,

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

write(' -----------'), nl,

write(' '), show2(X7),

write(' | '), show2(X8),

write(' | '), show2(X9), nl.

% show2(+Term)

% Write the term to current output

% Replace 0 by ' '.

show2(X) :-

X = 0, !,

write(' ').

show2(X) :-

write(X).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

2. Write a Prolog program to solve the Depth First Search Algorithm in Prolog
3. Write a Prolog program for Hill climbing search.
Lab Assignments :
4. Write a Prolog program to solve the Minimax search and Alpha-Beta Pruning
W Knowledge Based Expert System Using Prolog
e Lab Experiments :

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

e 1. Write a Prolog program for Knowledge-Based medical diagnostic expert system that is capable of
k diagnosing one of the following medical situations:
1 HIV:
0 - sore_throat
- headache
- fever
- rash
Pregnancy
- fatigue
- vomiting
- light_headedness
- increased_waistline
Flu
- headache
- fever
- tiredness
- nasal_discharge
Your system should function correctly even if the user inputs a synonym of one of the symptoms.

Lab Assignments:
2. Write a Prolog program to solve the Knowledge-Based animal identification for
implementing expert systems.

/* Animal identification game. */

go :- hypothesize(Animal),
write('I guess that the animal is: '),
write(Animal),
nl,
undo.

/* hypotheses to be tested */
hypothesize(cheetah) :- cheetah, !.
hypothesize(tiger) :- tiger, !.
hypothesize(giraffe) :- giraffe, !.
hypothesize(zebra) :- zebra, !.
hypothesize(ostrich) :- ostrich, !.
hypothesize(penguin) :- penguin, !.
hypothesize(albatross) :- albatross, !.
hypothesize(unknown). /* no diagnosis */

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

/* animal identification rules */


cheetah :- mammal,
carnivore,
verify(has_tawny_color),
verify(has_dark_spots).
tiger :- mammal,
carnivore,
verify(has_tawny_color),
verify(has_black_stripes).
giraffe :- ungulate,
verify(has_long_neck),
verify(has_long_legs).
zebra :- ungulate,
verify(has_black_stripes).

ostrich :- bird,
verify(does_not_fly),
verify(has_long_neck).
penguin :- bird,
verify(does_not_fly),
verify(swims),
verify(is_black_and_white).
albatross :- bird,
verify(appears_in_story_Ancient_Mariner),
verify(flys_well).

/* classification rules */
mammal :- verify(has_hair), !.
mammal :- verify(gives_milk).
bird :- verify(has_feathers), !.
bird :- verify(flys),
verify(lays_eggs).
carnivore :- verify(eats_meat), !.
carnivore :- verify(has_pointed_teeth),
verify(has_claws),
verify(has_forward_eyes).
ungulate :- mammal,
verify(has_hooves), !.
ungulate :- mammal,
verify(chews_cud).

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

/* how to ask questions */


ask(Question) :-
write('Does the animal have the following attribute: '),
write(Question),
write('? '),
read(Response),
nl,
( (Response == yes ; Response == y)
->
assert(yes(Question)) ;
assert(no(Question)), fail).

:- dynamic yes/1,no/1.

/* How to verify something */


verify(S) :-
(yes(S)
->
true ;
(no(S)
->
fail ;
ask(S))).

/* undo all yes/no assertions */


undo :- retract(yes(_)),fail.
undo :- retract(no(_)),fail.
undo.

2 ?- go.
Does the animal have the following attribute: has_hair? no.

Does the animal have the following attribute: gives_milk? |: no.

Does the animal have the following attribute: has_feathers? |: yes.

Does the animal have the following attribute: does_not_fly? |: yes.

Does the animal have the following attribute: has_long_neck? |: no.

Page No: Compiled By: Souvik Majumdar


Department of Computer Science & Engineering
RCC Institute of Information Technology, Kolkata
Canal South Road, Kolkata - 700015

Laboratory Experiment & Assignment Date of Assignment: 23.07.2018


Paper Name: Artificial Intelligence Lab Paper code: CS793C
Semester: 7th B.Tech(CSE) Academic Session: July-Dec 2018-19

Does the animal have the following attribute: swims? |: yes.

Does the animal have the following attribute: is_black_and_white? |: yes.

I guess that the animal is: penguin


true.

3 ?- go.
Does the animal have the following attribute: has_hair? no.

Does the animal have the following attribute: gives_milk? |: no.

Does the animal have the following attribute: has_feathers? |: no.

Does the animal have the following attribute: flys? |: no.

I guess that the animal is: unknown


true.

4 ?- go.
Does the animal have the following attribute: has_hair? yes.

Does the animal have the following attribute: eats_meat? |: yes.

Does the animal have the following attribute: has_tawny_color? |: yes.

Does the animal have the following attribute: has_dark_spots? |: yes.

I guess that the animal is: cheetah


true.

Page No: Compiled By: Souvik Majumdar

You might also like