0% found this document useful (0 votes)
32 views19 pages

Practical File AI

Uploaded by

sarthaksaini7400
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)
32 views19 pages

Practical File AI

Uploaded by

sarthaksaini7400
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/ 19

MEERUT INSTITUTE OF ENGINEERING &

TECHNOLOGY
Department of Computer Science and Engineering

Year:IV Semester:VII

Artificial Intelligence Lab – KCS751

LABMANUAL

MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
DepartmentofComputerScienceandEngineering

INDEX
S.No Practical’sName Date Remark
1 StudyofProlog.
2 Write simple fact for the statements using PROLOG.
3 Write predicates One converts centigrade temperatures to
Fahrenheit, the other checks if a temperature is below
freezing.
4 Write a program to solve the Monkey Banana problem.
5 WAP in turbo prolog for medical diagnosis and show the
advantage and disadvantage of green and red cuts.
6 WAP to implement factorial, Fibonacci of a given number.
7 Write a program to solve4-Queen problem.
8 Write a program to solve traveling salesman problem.
9 Write a program to solve water jug problem using LISP
MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.1

CourseCode:KCS751
Branch:CSE Semester:VII
Faculty :

OBJECTIVE:StudyofProlog.
PROLOG-PROGRAMMINGINLOGIC
PROLOG stands for Programming, In Logic — an idea that emerged in the early 1970’s
touselogicasprogramminglanguage.Theearlydevelopersof
thisideaincludedRobertKowaiskiatEdinburgh(onthetheoreticalside),MarrtenvanEmdenatEdinb
urgh(experimentaldemonstration) andAlianColmeraueratMarseilles(implementation).
DavidD.H.Warren’s efficientimplementation atEdinburghin themid-1970’s greatlycontributed
to the popularity of PROLOG. PROLOG is a programming language
centredaroundasmallsetofbasicmechanisms,Includingpatternmatching,treebaseddatastructurin
g and automaticbacktracking. This Small setconstitutes a surprisingly powerfuland flexible
programming framework. PROLOG is especially well suited for problems thatinvolve
objects-inparticular,structuredobjects-andrelationsbetweenthem.
SYMBOLICLANGUAGE
PROLOGisaprogramminglanguageforsymbolic,non-numericcomputation.Itisespecially 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: ifobject X is closer
to the observer than object Y. and object Y is closer than Z, then X must becloser than Z.
PROLOG can reason about the spatial relationships and their consistency
withrespecttothegeneralrule.FeatureslikethismakePROLOGapowerfullanguageforArtJIcia1La
nguageA1,)andnon-numericalprogramming.
There are well-known examples of symbolic computation whose implementation in
otherstandard languages took tens of pages of indigestible code, when the same algorithms
wereimplementedinPROLOG,theresultwasacrystal-clearprogrameasily fitting ononepage.
FACTS,RULESANDQUERIES
Progmmming in PROIOG is accomplished by creating a database of facts and rules
aboutobjects, their properties, and their relationships to other objects. Queries then can be
posedabout the objects and valid conclusions will be determined and returned by the
programResponses to user queries are determined through a form of inference control known
asresolution.
FOREXAIPLE:
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:grandf.gher(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
aqueryasymbol’?’statementssuchas:
?-parent(X,sam)Xann
?grandfather(X,Y)
X=jo,Y=sam
PROLOGINDISGININGEXPERTSYSTEMS
An expert system is a set of programs that manipulates encoded knowledge to solve
problemsinaspecializeddomainthatnormallyrequireshumanexpertise.Anexpertsystem’sknowle
dge is obtained from expert sources such as texts, journal articles. databasesetc andencoded in
a form suitable for the system to use in its inference or reasoning processes. Oncea 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 thesystem
PROLOG serves as a powerful language in designing expert systems because of
itsfollowingfeatures.
 Use ofknowledgeratherthandata
 Modificationofthe knowledgebasewithout recompilationofthecontrolprograms.
 Capableofexplainingconclusion.
 Symboliccomputationsresemblingmanipulationsofnaturallanguage.
 Reasonwithmeta-knowledge.
METAPROGRAMMING
A meta-program is a program that takes other programs as data.Interpreters and compilersare
examples of mela-programs. Meta-interpreter is a particular kind of meta-program:
aninterpreter for a language written in that language. So a PROLOG interpreter is an
interpreterforPROLOG,itself written in PROLOG.Duetoits symbol-manipulation
capabilities,PROLOG is a powerful language for meta-programming. Therefore, it is often
used as animplementation language for other languages. PROLOG is particularly suitable as a
languagefor rapid prototyping where we are interested in implementing new ideas quickly.
New ideasare rapidlyimplementedandexperimentedwith.

OUTCOME: Students will get the basic idea of how to program in prolog and its
workingenvironment.
MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName: Artificial Intelligence EXPERIMENTNO.2

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE: Writesimplefactfor following:


a. Ramlikesmango.
b. Seema isagirl.
c. BilllikesCindy.
d. Roseisred.
e. Johnownsgold.

Program:

Clauses
likes(ram
,mango).girl(seem
a).red(rose).likes(b
ill
,cindy).owns(john,
gold).

Output:

Goalqu
eries
?-
likes(ram,What).
What=mango
?-
likes(Who,cindy).
Who= cindy
?-
red(What).
What= rose
?-
owns(Who,What).
Who=john
What=gold.

OUTCOME: Studentwillunderstandhowtowritesimplefactsusingprolog.
MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.3

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE: Write
predicatesOneconvertscentigradetemperaturestoFahrenheit,theo
therchecks ifatemperatureisbelowfreezing.
Program:
Productionrules:
Arithmetic:

c_to_f fisc * 9/5 +32


freezing f<= 32

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

Output:
Queries:
?-
c_to_f(100,X).X
=212
Yes
?- freezing(15)
.Yes
?-
freezing(45).N
o

OUTCOME: Student will understand how to write a program using the rules.
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.4

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE:WriteaprogramtosolvetheMonkeyBananaproblem.
Imagine a room containing a monkey, chair and some bananas. That have been hanged
fromthe centre of ceiling. If the monkey is clever enough he can reach the bananas by placing
thechair directly below the bananas and climb on the chair .The problem is to prove the
monkeycan reach the bananas.The monkey wants it, but cannot jump high enough from the
floor. Atthe window of the room there is a box that the monkey can use. The monkey can
perform thefollowingactions:-
1) Walkonthefloor.
2) Climbthebox.
3) Pushtheboxaround(ifitisbesidethebox).
4) Graspthebananaif itisstandingontheboxdirectlyunder thebanana.
ProductionRules
can_reach clever,close.
get_on: can_climb.
under inroom,in_room,in_room,can_climb.
Close get_on,under|

tallParse Tree

Clauses:
in_room(bananas).in_roo
m(chair).in_room(monkey
).clever(monkey).can_clim
b(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.

OUTCOME: Studentwill understandhow tosolvemonkey banana problem using rules


inprolog.
MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.5

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE:WAPinturboprologformedicaldiagnosisandshowtheadvantageandd
isadvantageofgreenandredcuts.

Program:

Domains:disease,indicatio
n=symbolname-string

Predicates:hypothesis(name,dis
ease)symptom(name,indication)
response(char)
gogoo
nce

clauses
go:-
goonce
write("willyouliketotryagain(y/n)?"),response(Reply),
Reply='n'.
go.goonc
e:-
write("what is the patient's
name"),nl,readln(Patient),hypothesis(P
atient,Disease),!,write(Patient,"probabl
yhas",Disease),!,goonce:-
write("sorry, iamnotinapositiontodiagnose"),write("the
disease").
symptom(Patient,fever):-
write("does",Patient,"hasafever(y/n)?"),nl,r
esponse(Reply),
Reply='y',nl.symptom(P
atient,rash):-

write("does",Patient,"hasarash(y/n)?"),nl,response(Reply)
,
Reply='y',symptom(Patient_b
ody,ache):-
write("does",Patient,"hasabodyache(y/n)?"),nl,response(R
eply).
Reply='y',nl.symptom(Patient,r
unny_nose):-
write("does",Patient,"has a runny_nose
(y/n)?"),response(Reply),
Reply='y'hypothesis(Patient,f
lu):-
symptom(Patient,fever),symp
tom(Patient,body_ache),
hypothesis(Patient,common_cold):-
symptom(Patient,body_ache),Symp
tom(Patient,runny_nose).response(
Reply):-
readchar(Reply),
write(Reply).

Output:

makewindow(1,7,7"Expert Medical
Diagnosis",2,2,23,70),go.

OUTCOME:Studentwillunderstandhowto createaexpertsystemusing prolog.


MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.6

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE:WAPtoimplementfactorial,fibonacciofagivennumber.

Program:

Factorial:

factorial(0,1).facto

rial(N,F):-
N>0,
N1isN-1,
factorial(N1,F1),
FisN *F1.

Output:
Goal:
?-
factorial(4,X).X
=24

Fibonacci:

fib(0, 0).
fib(X, Y) :- X > 0, fib(X, Y,
_).fib(1,1,0).
fib(X, Y1, Y2) :-
X >1,
X1 isX-
1,fib(X1, Y2,
Y3),Y1isY2
+Y3.

Output:
Goal:
?-
fib(10,X).X
=55

OUTCOME:StudentwillunderstandtheimplementationofFibonacciandfactorialseriesusingpro
log.
MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.7

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE:Writeaprogramtosolve4-Queenproblem.

Program:
In the 4 Queens problem the object is to place 4 queens on a chessboard in such a way that
noqueens can capture a piece. This means that no two queens may be placed on the same
row,column,ordiagonal.

The nQueensChessboard.
domains
queen = q(integer,
integer)queens= queen*
freelist = integer*
board=board(queens,
freelist,freelist,freelist,freelist)predicates
nondetermplaceN(integer, board,
board)nondetermplace_a_queen(integer, board,
board)nondetermnqueens(integer)
nondetermmakelist(integer,freelist)
nondetermfindandremove(integer, freelist,
freelist)nextrow(integer,freelist,freelist)
clausesnqueens(
N):-
makelist(N,L),Di
agonal=N*2-1,
makelist(Diagonal,LL),placeN(N,board
([],L,L,LL,LL),Final),write(Final).
placeN(_,board(D,[],[],D1,D2),board(D,[],[],D1,D2)):-!.
placeN(N,Board1,Result):-
place_a_queen(N,Board1,Board2),
placeN(N,Board2,Result).place_a_
queen(N,
board(Queens,Rows,Columns,Diag1,Diag2),board([q(R,
C)|Queens],NewR,NewC,NewD1,NewD2)):-
nextrow(R,Rows,NewR),findandremove(C,Columns,Ne
wC),
D1=N+C-
R,findandremove(D1,Diag1,NewD1),D2=R+C-
1,findandremove(D2,Diag2,NewD2).findandre
move(X,[X|Rest],Rest).findandremove(X,[Y|Re
st],[Y|Tail]):-findandremove(X,Rest,Tail).
makelist(1,[1]).
makelist(N,[N|Rest]) :-
N1=N-1,makelist(N1,Rest).
nextrow(Row,[Row|Rest],Rest).

Output:

Goal:
?-
nqueens(4),nl.board([q(1,2),q(2,4),q(3,1),q(4,3),[],[],[7,4,1
],[7,4,1])
yes

OUTCOME: Studentwillimplement4-Queenproblemusingprolog.
MEERUTINSTITUTEOF ENGINEERING &TECHNOLOGY

LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.8

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE:Writeaprogramtosolvetravelingsalesmanproblem.

The following isthesimplified mapusedfortheprototype:

Program:

ProductionRules:-
route(Town1,Town2,Distance)
road(Town1,Town2,Distance).
route(Town1,Town2,Distance)
road(Town1,X,Dist1),route(X,Town2,Dist2),Distance=Dist1+Dist2,
domains
town =
symboldistance =
integerpredicates
nondeterm
road(town,town,distance)nondetermr
oute(town,town,distance)

clausesroad("tampa","housto
n",200).
road("gordon","tampa",300).
road("houston","gordon",100).road("houston","kansas_cit
y",120).
road("gordon","kansas_city",130).
route(Town1,Town2,Distance):-
road(Town1,Town2,Distance).rou
te(Town1,Town2,Distance):-
road(Town1,X,Dist1),route(X,To
wn2,Dist2),Distance=Dist1+Dist2
,!.
Output:
Goal:
route("tampa","kansas_city",X),
write("DistancefromTampatoKansasCityis",X),nl.

DistancefromTampatoKansasCityis320X=3
20

OUTCOME:Studentwillimplementtravellingsalesmenproblemusingprolog.
MEERUTINSTITUTEOF ENGINEERING
&TECHNOLOGY
LABMANUAL

CourseName:ArtificialIntelligence EXPERIMENTNO.9

CourseCode:KCS751 Branch:CSE Semester:VII

Faculty :Dr.SATISH BABU

OBJECTIVE: Write a program to solve water jug problem using LISP.

Program:
;returns the quantity in first
jug(defunget-first-jug(state)(car
state))

;returnsthequantityinsecondjug
(defunget-second-jug(state)(cadrstate))

;returns the state of two


jugs(defunget-state(fs)(listfs))

;checkswhethera givenstateisa goal


;GOALISTO GET4INSECONDJUG
(defunis-goal(state)
(eq(get-second-jug state)4))

;returnsallpossiblestatesthatcanbederived
;fromagivenstate(defunc
hild-states(state)
(remove-
null(list
(fill-first-jug
state)(fill-second-
jugstate)
(pour-first-second
state)(pour-second-
firststate)(empty-first-
jugstate)(empty-second-
jugstate))))

;remove the null


states(defunremove-
null(x)
(cond((nu
llx)nil)
((null(car x))(remove-null(cdr x)))
((cons(carx) (remove-null(cdrx))))))
;returnthestatewhenthefirstjugis filled(firstjugcanhold3)(defunfill-
first-jug(state)
(cond
((<(get-first-jug state)3)(get-state3(get-second-jug state))))))

;returnsthestatewhenthesecondjugis filled(secondjugcanhold5)(defunfill-
second-jug(state)
(cond
((<(get-second-jug state)5)(get-state(get-first-jug state)5))))

;returnsthestatewhenquantityinfirst
;ispouredtosecondjug
(defun pour-first-second
(state)(let ((f (get-first-jug
state))(s(get-second-
jugstate)))
(cond
((zerop f) nil); first jug is
empty((= s 5) nil); Second jug is
full((<=(+fs)5)
(get-state0(+fs)))
(t
;pourtofirstfromsecond(g
et-state(-(+fs)5)5)))))

;returnsthestatewhensecondjugispouredtofirst(defunpour
-second-first(state)
(let ((f (get-first-jug
state))(s(get-second-jug
state)))
(cond
((zerop s) nil); second jug is
empty((=f3)nil);secondjugisfull
((<=(+fs)3)
(get-state(+ fs)0))
(t
;pourtosecondfromfirst(g
et-state3(-(+ fs)3))))))

;returnsthestatewhenfirstjugisemptied(defun
empty-first-jug(state)
(cond
((>(get-first-jug state)0)(get-state0(get-second-jugstate)))))

;returnsthestatewhensecondjugisemptied(defune
mpty-second-jug(state)
(cond
((>(get-second-jug state)0)(get-state(get-first-jug state)0))))

;;;MAINFUNCTION
(defundfs(start-
statedepthlmt)(setf*node*0)
(setf*limit* lmt)
(dfs-nodestart-statedepth)
)
;dfs-node expands a node and calls dfs-children to recurse on
it(defundfs-node(statedepth)
(setf *node* (+ 1
*node*))(cond
((is-goal state) (list
state))((zeropdepth)nil)
((>*node**limit*)nil)
((let((goal-child(dfs-children(child-statesstate) (-depth1))))
(and goal-child (cons state goal-child)))) ;for back-tracking if the branch don't have a
goalstate
))

;dfs-childrenexpandseachnoderecursivelyandgiveit
;todfs-nodetoprocess
(defundfs-children (states
depth)(cond
((nullstates)nil)
((dfs-node (car states)
depth))((dfs-
children(cdrstates)depth))))

(print"ENTERYOURINPUTAS")
(print"(dfsstart_statedepthlimit)")

OUTCOME:Studentwillimplementwater-jugproblemusingLisp.

You might also like