CMR TECHNICAL CAMPUS
UGC AUTONOMOUS
Kandlakoya(V), Medchal Road, Hyderabad – 501 401
Accredited by NBA and NAAC with A Grade
Approved by AICTE, New Delhi and Affiliated to JNTU, Hyderabad
Department of CSE(AI & ML)
Course Name : Artificial Intelligence Lab
Course Code : 20AI604PC
Course Designation : Core
Credits : 4
Prerequisites : Data Mining Lab
Prepared By
Dr. G Vinoda Reddy
Professor
Course Coordinator
Course Objectives:
1. To provide a strong foundation of fundamental concepts in Artificial Intelligence.
2. To apply the techniques in applications which involve perception, reasoning and learning.
Course Outcomes:
After completion of the course, the student will be able to:
1. Implement different AI algorithms using LISP/PROLOG
2. Develop an Expert System using JESS/PROLOG
List of Experiments
S.No Practical’s Name
1 Study of Prolog. Implementation of DFS for water jug
problem using LISP/PROLOG
2 Implementation of BFS for tic-tac-toe problem using
LISP/PROLOG/Java
3 Implementation of TSP using heuristic approach using
Java/LISP/Prolog
4 Implementation of Simulated Annealing Algorithm using
LISP/PROLOG
5 Implementation of Hill-climbing to solve 8- Puzzle
Problem
6 Implementation of Monkey Banana Problem using
LISP/PROLOG
7 Implementation of A* Algorithm using LISP/PROLOG
8 Implementation of Hill Climbing Algorithm using
LISP/PROLOG
Program1: Implementation of DFS for water jug problem using LISP/PROLOG
Program:
;returns the quantity in first jug (defun get-
first-jug (state) (car state))
;returns the quantity in second jug
(defun get-second-jug (state) (cadr state))
;returns the state of two jugs (defun
get-state (f s) (list f s))
;checks whether a given state is a goal
; GOAL IS TO GET 4 IN SECOND JUG
(defun is-goal (state)
(eq (get-second-jug state) 4))
;returns all possible states that can be derived
;from a given state (defun child-
states (state)
(remove-null
(list
(fill-first-jug state)
(fill-second-jug
state)
(pour-first-second state)
(pour-second-first state)
(empty-first-jug state)
(empty-second-jug
state))))
;remove the null states (defun
remove-null (x)
(cond
((null x) nil)
((null (car x)) (remove-null (cdr x)))
((cons (car x) (remove-null (cdr x))))))
;return the state when the first jug is filled (first jug can hold 3) (defun fill-
first-jug (state)
(cond
((< (get-first-jug state) 3) (get-state 3 (get-second-jug state))))))
;returns the state when the second jug is filled (second jug can hold 5) (defun fill-
second-jug (state)
(cond
((< (get-second-jug state) 5) (get-state (get-first-jug state) 5))))
;returns the state when quantity in first
;is poured to second jug
(defun pour-first-second
(state) (let ( (f (get-first-jug
state)) (s (get-second-jug
state)))
(cond
((zerop f) nil) ; first jug is empty
((= s 5) nil) ; Second jug is full
((<= (+ f s) 5)
(get-state 0 (+ f s)))
(t ; pour to first from
second (get-state (- (+ f s) 5)
5)))))
;returns the state when second jug is poured to first (defun
pour-second-first (state)
(let ( (f (get-first-jug state))
(s (get-second-jug state)))
(cond
((zerop s) nil) ; second jug is empty
((= f 3) nil) ; second jug is full
((<= (+ f s) 3)
(get-state (+ f s) 0))
(t ;pour to second from
first (get-state 3 (- (+ f s)
3))))))
;returns the state when first jug is emptied (defun
empty-first-jug (state)
(cond
((> (get-first-jug state) 0) (get-state 0 (get-second-jug state)))))
;returns the state when second jug is emptied (defun
empty-second-jug (state)
(cond
((> (get-second-jug state) 0) (get-state (get-first-jug state) 0))))
;;;MAIN FUNCTION
(defun dfs (start-state depth lmt)
(setf *node* 0)
(setf *limit* lmt)
(dfs-node start-state depth)
)
;dfs-node expands a node and calls dfs-children to recurse on it (defun dfs-node (state depth)
(setf *node* (+ 1 *node*))
(cond
((is-goal state) (list state))
((zerop depth) nil)
((> *node* *limit*) nil)
((let ((goal-child (dfs-children (child-states state) (- depth 1))))
(and goal-child (cons state goal-child)))) ;for back-tracking if the branch don't have a goal state
))
;dfs-children expands each node recursively and give it
;to dfs-node to process
(defun dfs-children (states depth)
(cond
((null states) nil)
((dfs-node (car states) depth))
((dfs-children (cdr states)
depth))))
(print "ENTER YOUR INPUT AS")
(print "(dfs start_state depth limit)")
Program2: Implementation of BFS for tic-tac-toe problem using LISP/PROLOG/Java
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,_,_].
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).
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.
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, N, Board) :- write('Illegal move.'), nl.
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).
?-playo.
you play x by entering integer positions followed by a period.
[1,2,3]
[4,5,6]
[7,8,9]
1:5
[_,_,_]
[_,x,_]
[_,_,_]
1:3
[0,_,x]
[_,x,_]
[_,_,_]
[0,_,x]
[_,x,_]
[0,_,_]
1:4
[0,_,x]
[x,x,_]
[0,_,_]
[0,_,x]
[x,x,0]
[0,_,_]
1:9
[0,_,x]
[x,x,0]
[0,_,x]
[0,0,x]
[x,x,0]
[0,_,x]
1:8
[0,0,x]
[x,x,0]
[0,x,x]
cats game!
[0,0,x]
[x,x,0]
[0,x,x]
Program3 :Implementation of TSP using heuristic approach using Java/LISP/Prolog
len([],0)
len([HIT],N):-len(T,X),N is x+1.
best_path(visited,Total):-path(start,fin,[start],visited,0,Total)
path(start,fin,currentloc,visited,cost n,total):-
edge(start,fin,distance),
reverse([fin/current loc],visited)
Total is cost n+Distance
shortest_path(path):- setof(cost_path,best_path(path,cost),pick(Harder,path)
best(cost_Holder,Bcost_,cost_holder):-
cost < Bcost
best( _,x,x)
pick([cost_holder[R],x):-pick(R, Bcost_Bholder),
best(cost_holder,Bcost_Bholder x)
pick([x],x).
OUTPUT:
1? - [prolog]
1? - shortest_path(path)
path = 20 _ [a,b,d,e,b,c,a]
Program 4: Implementation of Simulated Annealing Algorithm using LISP/PROLOG
from numpy import as array,exp
from numpy.random import randn,rand,seed
def objective(X):
return x[0]**2.0
def simulated_annealing(objective,bounds,n_iterations,step_size,temp)
but=bpunds[i,0]+bounds[:,0]
best_wal=objective(best)
cuee,curr_eval=but,best_eval
for i in range(n_iterations):
candidate=curr+rand(len(bounds)0*
step_size
candidate_eval=objective(candidate)
if candidate_eval<but_eval
but,but_eval=candidate,candidate_eval
print('>%df(%s)=%5f;%li,but,best_eval)
diff=candidate_eval-curr_eval
t=temp/float(i+1)
metropolis=exp(-diff/t)
if diff < 0 or rand() < metropolis:
curr, curr_eval = candidate, candidate_eval
return [best, best_eval]
seed(1)
bounds=as array([[-5.0,5.0]])
n_iterations = 100
step_size-0.1000
temp=0
best_score=simulated_annealing(objective,bounds,n_iterations,step_size,temp)
print('done!')
print('f(%s)=%f' %(but,score)
OUTPUT:
34 f([-0.78753544])=0.62021
35 f([-0.76014239])=0.59158
37 f([-0.68574854])=0.47025
39 f([-0.64795647])=0.41987
42 f([-0.41775702])=0.17452
50 f([-0.15799045])=0.02496
67 f([-0.09238208])=0.00853
75 f([-0.05129162])=0.00203
93 f([-0.02854417])=0.00081
225 f([-0.00044965])=0.0000
512 f([-0.00013605])=0.0000
done !
f([0.00013605])=0.00000
im:
Program5: Implementation of Hill-climbing to solve 8- Puzzle Problem
:-Dp(400,yfx;'#').
solve(state,soln):- F_function(state,0,F),search([state#0F#B],s),reverse(s,soln).
F_function(state,D,F):- F id D.
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(R,open2,open3).
insert_all([],open,open).
repeat_node(p#_#_#,[p#_#_#_1_]).
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)
goal(1/2/3/8/0/4/7/6/5).
left(A/O/C/D/E/F/H/I/J,O/A/C/D/E/F/H/I/J).
left(A/B/C/D/O/F/H/I/J,A/B/C/O/E/F/H/I/J).
left(A/O/C/D/E/F/O/I/J,A/B/C/D/E/O/H/I/J).
up(A/B/C/O/E/F/H/I/J,O/B/C/A/E/F/H/I/J).
up(A/B/C/D/O/F/H/I/J,A/O/C/A/E/F/H/I).
up(A/ B/ C/ D/ E/ F/H/O /J, A/B/C/D/0/F/H/E/J)
up(A/B/0/D/E/F/ H/I|J, A/ B/ C/0 / F /H/I/J)
up (A/ B/C/0/E/ F/H/I/J, A/B/C/0/ E/F/H/I/D).
h_function ( Puzz, H): - P_fcn (Puzz, P),
s_ fcn (Puzz, s),
H is P+ 3 * S.
move (P, c, Left):-left (P, c).
move (P, C, right) :-right (P, C).
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 + Pi.
S_fun (A/ B/ C/D / E/F/G/H/I , s) : -
s_aur(A, B, SI) , s_ aux (b, c, S2),
s_ aux (F, I, S4) , s_ aux (I, H, S5).
puzzle(P):-solve (P,S),
animate (P, S),
message
animate (P, s):-initialize (P), cursor (1,2) ,
write (s) , cursor ( 1, 22) .
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 (D, 20, 10)),
draw _ all.
draw (_, _, ) :
cursor (X , Y).
write (P) ,
draw_row ( X1, Y , R).
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).
left (obi):-hide (obj) ,
retract (location (obj, X1, 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
draw (obj ).
Output
1?-solve puzzle ([[1 ,3,4], [8, 0,5], [7, 2, 6]].
[[1,2, 3] , [8, 0,4], [7, 6, 5]], (0,8).
134
805
726
134
825
706
134
825
760
134
820
765
130
824
765
103
824
765
123
804
765
Cost=6
Program 6: Implementation of Monkey Banana Problem using LISP/PROLOG
Imagine a room containing a monkey, chair and some bananas. That have been hanged from the
centre 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 Parse Tree
move(state(
middle,onbox,middle,hasnot),
grasp,
state(middle,onbox,middle,has)).
move(state(p,onfloor,P,H),
climb,
state(P,onfloor,P,H)).
move(state(P1,onfloor,P1,H),
drag(P1,P2),
state(P2,onflor,P2,H)).
move(state(P1,onfloor,B,H),
walk(P1,P2),
state(P2,onfloor,B,H)).
canget(state(_,_,_,has)).
canget(state,1):
move(state 1,_,state 2).
canget(state 2).
OUTPUT:
?- canget(state(atdoor,onfloor,atwindow,hasnot)).
true.
?-trace
true.
[trace] ?-canget(state(atdoor,onfloor,atwindow,hasnot))
call:(10) canget(atdoor,onfloor,atwindow,hasnot))?
call:(11) canget(state(atdoor,onfloor,atwindow,hasnot),_9038,_8978)?creep
exit:(11) move(state(atdoor,onfloor,atwindow,hasnot),
walk(atdoor,_9742), state(_9742,onfloor,atwindow,hasnot))?
call:(11) canget(state(_9742,onfloor,atwindow,hasnot))?
exit:(12) move(state(_9742,onfloor,atwindow,hasnot),_11322,_11262)?creep
call:(12) canget(state(atwindow,onbox,atwindow,hasnot))?creep
call:(13) move(state(atwindow,onbox,atwindow,hasnot),_13600,_13540)?creep
fail:(13) move(state(atwindow,onbox,atwindow,hasnot),_14358,_13540)?creep
fail:(12) canget(state(atwindow,onbox,atwindow,hasnot))?creep
Redo:(12) move(state(_9742,onfloor,atwindow,hasnot),_15866,_11262)?creep
exit:
(12)move(state(atwindow,onfloor,atwindow,hasnot),drag(atwindow,_16570,state(_16570,onfloor,_16570,has
not))?creep
call:(12) canget(state(atwindow,onfloor,_16570,hasnot))?creep
call:(13) move(state(_16570,onbox,_16570,hasnot),_20428,_20368)?creep
exit:(14) move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox,middle,has))?creep
call:(14) canget(state(middle,onbox,middle,has))?creep
exit:(14) canget(state(middle,onbox,middle,has))?creep
exit:(13) canget(state(middle.onbox,middle,hasnot))?creep
exit:(12) canget(state(middle,onfloor,middle,hasnot))?creep
Clauses:
in_room(bananas).
in_room(chair).
in_room(monkey).
clever(monkey).
can_climb(monkey, chair).
tall(chair).
can_move(monkey, chair, bananas).
can_reach(X, Y):-
clever(X),close(X, Y).
get_on(X,Y):- can_climb(X,Y).
under(Y,Z):-
in_room(X),in_room(Y),in_room(Z),can_climb(X,Y,Z).
close(X,Z):-get_on(X,Y),
under(Y,Z);
tall(Y).
Output:
Queries:
?- can_reach(A, B).
A = monkey.
B = banana.
?- can_reach(monkey, banana).Yes.
Program 7: Implementation of A* Algorithm using LISP/PROLOG
PROBLEM STATEMENT:
Given a list of cities and the distance between each pair of cities,what is the shortest possible route that visits
each city exactly once and returns to the origin city.
THE A* algorithm:
The central algorithm idea in the so called A* algorithm is to guide best-first search both by
.the ultimate to the goal a given by heunistic approach.
.the cost of the path developed so far.
Let n be a node,g(n)-cost of moving from initial to n along the current pat is h(n),the estimated cost of
reaching a goal node from n,defining f(n) as
f(n)=g(n)+h(n)
Initial State:
salesman at initial state.
Goal State:
Reaching initial state by covering all cities.
Actions to be performed:
.checking all the possible ways to reach the final state.
.Calculating path cost of all paths.
.Getting best path for travelling.
Program:
edge(a,b,3)
edge(a,c,4)
edge(a,d,2)
edge(a,e,7)
edge(b,c,4)
edge(b,d,6)
edge(b,e,3)
edge(c,d,5)
edge(c,e,8)
edge(d,e,6)
edge(b,a,3)
edge(c,a,4)
edge(d,a,2)
edge(e,a,7)
edge(c,b,4)
edge(d,b,6)
edge(e,b,3)
edge(d,c,5)
edge(e,c,8)
edge(e,d,b)
edge(a,b,2)
edge(a,d,1)
len([],0)
len([H17],N):-len(T,X),N is X+1
best-path(visited,Total):-path(start,fin,[start],visited,0,total)
path(start,fin,currentloc,visited,costn,Total):-
edge(start,fin,distance),reverse([fin|current loc],visited),len(visited,Q),(Q\=7->Total is 100000;
Total is costn + distance
shortest_path(Path):-setof(cost_path,best_path(cost,Holder),pick(Holder,path).
best(cost_Holder,Bcost-,cost Holder):-cost<Bcost,!.
best(-,x,X)
pick([cost_Holder[R],X):-
pick(R,Bcost_Bholder),
best(cost_Holder,Bcost-Bholder,X),!.
pick([X],X)
Output
1?-[prolog]
1?-shortest_path(Path).
path=20 -[a,h,d,e,b,c,a].
Program 8: Implementation of Hill Climbing Algorithm using LISP/PROLOG
Import random
def randomSolution(tsp):
cities=list (range(len(tsp)))
Solution= []
for I in range (len (tsp)):
randomcity =cities[random.randint(0,len(cities)-1)]
solution.append(randomcity)
cities.remove(randomcity)
return solution
def routelength(tsp,solution):
routelenght = 0
for I in range (len(solution)):
routelength += tsp[solution[i-1]][solution[i]]
return routelength
def getNeighbours(solution):
neighbours = []
for I in range(len(solution)):
for j in range(i+1,len(solution)):
neighbours =solution.copy()
neighbour[i]=solution[j]
neighbour[j]=solution[i]
return neighbours
def getbestNeighbour(tsp,neighbours):
while BestNeighbourRoutelength<currentRoutelength:
currentSolution=bestNeighbour
currentRouteLength=bestNeighbourRouteLength
neighbours=getNeighbours(currentSolution)bestNeighbour
BestNeighbourRouteLength=getbestNeighbour (tsp, neighbour)
return currentSolution, currentRouteLength
def main ():
tsp=[
[0,400,500,300]
[400, 0,300,500]
[500, 300, 0, 400]
[300, 500, 400, 0]
]
print (hillclimbing (tsp))
If_name_ == “_main_”:
main ()
Output:
([0, 1, 2, 3], 400)