AI Practicals
AI Practicals
a
g
Computer Science & Engineering Department
e
|
(AY: 2023-24)
1
Subject In charge: Prof.V.D.Gaikwad
CO3: Student will able to Solve problem using depth first search..
CO4: Student will able to Solve problem using best first search.
CO5: Student will able to Solve 8-puzzle problem using best first search.
CO6: Student will able to Solve Robot (traversal) problem using means End Analysis.
Study of Programming languages, namely Student will able to Implement the Program using
1 PROLOG.
PROLOG.
2 Write a program to solve 8 queens problem. Student will able to Solve 8 Queens Problem.
4
Program 1 : Study of PROLOG. Write the following programs using PROLOG Using Turbo Prolog
Topics:
a) Basics of Turbo Prolog
b) Intro to Prolog programming
P c) Running a simple program
a
g
• Prolog is a logical programming language and stands for PROgramming in LOGic
e • Created around 1972
| • Preferred for AI programming and mainly used in such areas as:
5 o Theorem proving, expert systems, NLP, …
• Logical programming is the use of mathematical logic for computer programming.
5
Dialog
• When a Prolog program is executing, output will be shown in the Dialog Panel
Message
• The Message Panel keeps the programmer up to date on processing activity.
P Trace
a • The Trace Panel is useful for finding problems in the programs you create.
g
e
|
6 Prolog Clauses
Any factual expression in Prolog is called a clause.
There are two types of factual expressions: facts and rules
• There are three categories of statements in Prolog:
▪ Facts: Those are true statements that form the basis for the knowledge base.
▪ Rules: Similar to functions in procedural programming (C++, Java…) and has the form of
if/then.
▪ Queries: Questions that are passed to the interpreter to access the knowledge base and start the
program.
Facts…
Syntax rules:
1. The names of all relationships and objects must begin with a lower case letter. For example: likes, john,
rachel.
2. The relationship is written first, and the objects are written separated by commas, and the objects are
enclosed by a pair of round brackets.
3. The character ‘.’ must come at the end of each fact.
6
Terminology:
1. The names of the objects that are enclosed within the round brackets in each fact are called arguments.
2. The name of the relationship, which comes just before the round brackets, is called the predicate.
6. Remember that we must determine how to interpret the names of objects and relationships.
Variables
• Variables take the place of constants in facts.
• Variables begin with upper case letters.
• Contains the clauses that define the program – facts and rules.
Predicates Section
• Predicates (relations) used in the clauses section are defined.
• Each relation used in the clauses of the clauses section must have a corresponding predicate definition in
the predicates section. Except for the built in predicates of Turbo Prolog.
Turbo Prolog requires that each predicate in the predicate section must head at least one clause in the
clauses section.
A predicate definition in the predicates section does not end with a period.
Predicate definitions contain different names than those that appear in the clauses section. Make sure that
the predicate definition contains the same number of names as the predicate does when it appears in the
clauses section.
A Turbo Prolog may also have a domains section. In this section the programmer can define the type of each
object.
Examples:
Clauses Section – likes(tom, anna).
7
Predicates Section – likes(boy, girl)
Domains Section – boy, girl = symbol
It is possible to omit the domains section by entering the data types of objects in the predicates section.
likes(symbol,symbol)
However, this might make the program harder to read especially if the predicate associates many objects.
P
a
Simple Program
g
e domains
| disease,indication = symbol
8 predicates
symptom(disease, indication)
clauses
symptom(chicken_pox, high_fever).
symptom(chicken_pox, chills).
symptom(flu, chills).
symptom(cold, mild_body_ache).
symptom(flu, severe_body_ache).
symptom(cold, runny_nose).
symptom(flu, runny_nose).
symptom(flu, moderate_cough).
8
displayed. In Prolog, False indicates a failure to find a match using the current database – not that the goal is
untrue.
Variables Revisited
Variables are used in a clause or goal to specify an unknown quantity. Variables enable the user to ask more
informative questions. For example, if we wanted to know for which diseases, runny_nose was a symptom –
P type in
a Goal: symptom(Disease, runny_nose).
g
Turbo Prolog will respond
e
| Disease = cold
9 Disease = flu
2 Solutions
Goal:
To find the two solutions Turbo Prolog began at the start of the clauses section and tried to match the goal
clause to one of the clauses. When a match succeeded, the values of the variables for the successful match was
displayed. Turbo prolog continued this process until it had tested all predicates for a match with the specified
goal.
If you wish Prolog to ignore the value of one or more arguments when determining a goal’s failure or success
then you can use the anonymous variable “_” (underscore character).
Ex -
Goal: symptom(_, chills).
True
Goal:
Matching
Two facts match if their predicates are the same, and if their corresponding arguments are the same.
When trying to match a goal that contains an uninstantiated variable as an argument, Prolog will allow that
argument to match any other argument in the same position in the fact.
If a variable has a value associated with a value at a particular time it is instantiated otherwise it is
uninstantiated.
Heuristics
◼ A method to help solve a problem, commonly informal.
◼ It is particularly used for a method that often rapidly leads to a solution that is usually reasonably close
to the best possible answer.
◼ Heuristics are "rules of thumb", educated guesses, intuitive judgments or simply common sense.
hate(c,d).
hate(m,n).
9
hate(f,g).
Output:-
P
a
g
e
|
10
12
PROGRAM 2 : Steps for 8-queen problem
STEP 1 : Represent the board positions as 8*8 vector , i.e., [1,2,3,4,5,6,7,8]. Store the set
P of queens in the list ‘Q’.
a STEP 2 : Calculate the permutation of the above eight numbers stored in set P.
g STEP 3 : Let the position where the first queen to be placed be (1,Y), for second be
e (2,Y1) and so on and store the positions in Q.
| STEP 4 : Check for the safety of the queens through the predicate , ‘noattack ()’.
11 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.
12
permutation([1,2,3,4,5,6,7,8],Q),
safe(Q).
safe([]). /*Q is safe such that no queens attack each other*/
safe([Q|others]):-
safe(others),
P noattack(Q,others,1).
a noattack(_,[],_). /*to find if the queens are in same row, column or
g diagonal*/
e noattack(Y,[Y1|Ydist],Xdist):-
| Y1-Y<>Xdist,
12 Y-Y1<>Xdist,
dist1=Xdist,
noattack(Y,Ydist,dist1).
Output
goal: -solution(Q).
Q=[“3”,”8”,”4”,”7”,”1”,”6”,2”,”5”]
13
PROGRAM 3 : Write a program of depth first search
domains
X=symbol
P Y=symbol*
a predicates
g child(X,X)
e childnode(X,X,Y)
| path(X,X,Y)
13
clauses
child(a,b). /*b is child of a*/
child(a,c). /*c is child of a*/
child(a,d). /*d is child of a*/
child(b,e). /*b is child of b*/
child(b,f). /*f is child of b*/
child(c,g). /*g is child of c*/
path(A,G,[A|Z]):- /*to find the path from root to leaf*/
childnode(A,G,Z).
childnode(A,G,[G]):- /*to determine whether a node is child of other*/
child(A,G).
childnode(A,G,[X|L]):-
child(A,X),
childnode(X,G,L).
goal:-path(a,e,L).
L=[“a”,”b”,”e”]
13
PROGRAM 4 : Solve any problem using best first search
In both breadth-first search and depth-first search, the purpose of search is to find a goal state from the initial
state
as quickly as possible. Since the nodes in the queue are examined from the front, the fastest solution occurs
P when
a the goal node very quickly finds its way to the front of the queue. If this happens during Depth or Breadth first
g search, it will be a matter of luck rather than design. To arrange for the goal node to be examined as soon as
e
possible, we can add the successors to the queue and then sort it with the aim of placing the best successor, i.e.
|
14
the
successor that will lead soonest to the goal, at the front of the queue.
This leads to a generalisation of both Depth-First and Breadth-First search that consists of arranging candidate
nodes into a priority queue instead of a FIFO queue. This means that nodes are ordered according to some
comparison
operation, and the node with the highest priority or lowest cost is selected. In the AI literature, priority first
search is known as best first search.
pfs(Origin, Visited) :- pfs3([Origin], % INITIAL PRIORITY QUEUE
[], % LIST OF NODES VISITED SO FAR
RevVisited), % SOLUTION LIST OF NODES
reverse(RevVisited, Visited).
pfs3([Node|_], History, [Node | History]) :- goal(Node).
pfs3([Node|RestQ], History, RevVisited) :-
not goal(Node),
findall(NextNode,
(successor(Node, NextNode),
not member(NextNode, History),
not member(NextNode, RestQ)),
Successors), %LIST OF SUCCESSORS OF Node
addPriorityQ(RestQ, Successors, PriorityQ), %MAKE NEW PRIORITY QUEUE
pfs3(PriorityQ, [Node | History], RevVisited).
addPriorityQ(L1, Q1, Q2) :- append(L1, Q1, L2),
sortQ(L2, Q2).
lessthan(STATE1, STATE2) :- %STATE1 IS BETTER THAN STATE2
... %COMPLETE ACCORDING TO PROBLEM
After each swap, the new list is closer to a sorted list.
bubblesort(List, Sorted):-
swap(List, List1), !,
bubblesort(List1,Sorted).
bubblesort(Sorted, Sorted). %LIST SORTED
swap([X, Y | Rest], [Y, X | Rest]):- %SWAP FIRST PAIR
21
lessthan(X, Y).
swap([Z | Rest],[Z | Rest1]):- %SWAP PAIR IN TAIL
swap(Rest, Rest1).
Insertion sort. To sort a non-empty list,
• Sort the tail.
• Insert the head into the sorted tail at such a position that the resulting list is sorted.
insertsort([], []).
insertsort([X|T], Sorted):-
insertsort(T, SortedT), %SORT THE TAIL
14
insert(X, SortedT, Sorted). %INSERT X
insert(X, [Y|Sorted], [Y|Sorted1]):-
lessthan(X,Y), !,
insert(X, Sorted, Sorted1).
insert(X, Sorted, [X|Sorted]).
P
a
g
e
|
15
15
PROGRAM 5 : Write a program to solve 8-Puzzle problem.
The title of this section refers to a familiar and popular sliding tile puzzle that has been around for at least forty
years. The most frequent older versions of this puzzle have numbers or letters an the sliding tiles, and the player
is supposed to slide tiles into new positions in order to realign a scrambled puzzle back into a goal alignment. For
P illustration, we use the 3 x 3 8-tile version, which is depicted here in goal configuration
a
g
e
7 2 3
| 4 6 5
16
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).
Production Rules :-
h_function(Puzz,H) → p_fcn(Puzz,P), s_fcn(Puzz,S),H is P + 3*S.
s_aux(0,0) → cut
s_aux(X,Y,0) :- Y is X+1, !.
s_aux(8,1,0) :- !.
16
The heuristic function we use here is a combination of two other estimators: p_fcn, the Manhattan distance
function, and s_fcn, the sequence function, all as explained in Nilsson (1980), which estimates how badly out- of-
sequence the tiles are (around the outside).
h_function(Puzz,H) :- p_fcn(Puzz,P),
s_fcn(Puzz,S),
P H is P + 3*S.
a The 'move' predicate is defined as follows.
g move(P,C,left) :- left(P,C).
e move(P,C,up) :- up(P,C).
| move(P,C,right) :- right(P,C).
17 move(P,C,down) :- down(P,C).
Here is the code for p and s.
%%% Manhattan distance
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.
s_aux(0,0) :- !.
s_aux(_,1).
s_aux(X,Y,0) :- Y is X+1, !.
s_aux(8,1,0) :- !.
s_aux(_,_,2).
The Prolog program from the previous section and the program outlined in this section can be used as an 8-
puzzle solver.
?- solve(0/8/1/2/4/3/7/6/5, S).
17
P
a
g
e
|
18
Solution:
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 ).
18
PROGRAM 6 :
Means-Ends Analysis (MEA) is a technique used in Artificial Intelligence for controlling search in problem
solving computer programs. It is also a technique used at least since the 1950s as a creativity tool, most frequently
mentioned in engineering books on design methods. Means-Ends Analysis is also a way to clarify one's thoughts
P when embarking on a mathematical proof.
a Problem-solving as search
g An important aspect of intelligent behavior as studied in AI is goal-based problem solving, a framework in
e which the solution of a problem can be described by finding a sequence of actions that lead to a desirable goal.
| A goal-seeking system is supposed to be connected to its outside environment by sensory channels through
19 which it receives information about the environment and motor channels through which it acts on the
environment. (The term "afferent" is used to describe "inward" sensory flows, and "efferent" is used to describe
"outward" motor commands.) In addition, the system has some means of storing in a memory information about
the state of the environment (afferent information) and information about actions (efferent information). Ability
to attain goals depends on building up associations, simple or complex, between particular changes in states
and particular actions that will bring these changes about. Search is the process of discovery and assembly of
sequences of actions that will lead from a given state to a desired state. While this strategy may be appropriate
for machine learning and problem solving, it is not always suggested for humans (e.g. cognitive load theory and
its implications).
How MEA works
The MEA technique is a strategy to control search in problem-solving. Given a current state and a goal state, an
action is chosen which will reduce the difference between the two. The action is performed on the current state to
produce a new state, and the process is recursively applied to this new state and the goal state. Note that, in order
for MEA to be effective, the goal-seeking system must have a means of associating to any kind of detectable
difference those actions that are relevant to reducing that difference. It must also have means for detecting the
progress it is making (the changes in the differences between the actual and the desired state), as some attempted
sequences of actions may fail and, hence, some alternate sequences may be tried. When knowledge is available
concerning the importance of differences, the most important difference is selected first to further improve the
average performance of MEA over other brute-force search strategies. However, even without the ordering of
differences according to importance, MEA improves over other search heuristics (again in the average case) by
focusing the problem solving on the actual differences between the current state and that of the goal.
Some AI systems using MEA
The MEA technique as a problem-solving strategy was first introduced in 1963 by Allen Newell and Herbert
Simon in their computer problem-solving program General Problem Solver (GPS). In that implementation, the
correspondence between differences and actions, also called operators, is provided a priori as knowledge in the
system. (In GPS this knowledge was in the form of table of connections.) When the action and side-effects of
applying an operator are penetrable, the search may select the relevant operators by inspection of the operators
and do without a table of connections. This latter case, of which the canonical example is STRIPS, an automated
planning computer program, allows task-independent correlation of differences to the operators which reduce
them.
19
PROGRAM 7 : Write a program to solve traveling salesman problem.
P
a
g
e
|
20
Production Rules:-
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 = symbol
distance = integer
predicates
nondeterm road(town,town,distance)
nondeterm route(town,town,distance)
clauses
road("tampa","houston",200).
road("gordon","tampa",300).
road("houston","gordon",100).
road("houston","kansas_city",120).
road("gordon","kansas_city",130).
route(Town1,Town2,Distance):-
road(Town1,Town2,Distance).
route(Town1,Town2,Distance):-
road(Town1,X,Dist1),
route(X,Town2,Dist2),
Distance=Dist1+Dist2,
!.
goal
route("tampa", "kansas_city", X),
write("Distance from Tampa to Kansas City is ",X),nl.
21
PROGRAM 1 : Program to add two numbers.
P
predicates
a
g
e
add
|
22 clauses
add:-write("input first number"),
readint(X),
write("input second number"),
readint(Y),
Z=X+Y,write("output=",Z).
Output:-
22
PROGRAM 2 :Program to categorise animal characteristics.
predicates
P small(symbol)
a
g
large(symbol)
e color(symbol,sy
|
23 mbol)
clauses
small(rat).
small(cat).
large(lion).
color(dog,bl
ack).
color(rabbit,
white).
color(X,dark
):-
color(X,black);color(X,brown).
Output:-
23
PROGRAM 3 : Program to read address of a person using compound variable.
domains
person=address(name,street,city,state,zip)
P
a name,street,city,state,zip=String
g
e predicates
|
24 readaddress(per
son) go
clauses
go:-
readaddress(Address),nl,write(Address),nl,nl,write("Accept(y/n)?"),readc
har(Reply),Reply='y',!. go:-
nl,write("please re-enter"),nl,go.
readaddress(address(N,street,city,
state,zip)):-
write("Name:"),readln(N),
write("Street:"),readln(street),
write("City:"),readln(city),
write("State:"),readln(state),
write("Zip:"),readln(zip).
Output:-
24
PROGRAM 4 : Program of fun to show concept of cut operator .
Predicates
P
a
g
e
fun(integer,integer)
|
25 clauses
fun(Y,1):-Y<3,!.
fun(Y,2):-Y>3,Y<=10,!.
fun(Y,3):-Y>10,!.
Output:-
25
PROGRAM 5 : Program to count number of elements in a list .
domains
x=integer
list=integer*
P predicates
a count(list,x)
g clauses
e count([],0).
|
count([_|T],N):-count(T,N1),N=N1+1.
26
Output:-
26
PROGRAM 6 : Program to reverse the list .
domains
x=integer
list=integer*
P
a
predicates
g append(x,list,list)
e rev(list,list)
| clauses
27 append(X,[],[X]).
append(X,[H|T],[H|T1]):-append(X,T,T1).
rev([],[]).
rev([H|T,rev):-rev(T,L),append(H,L,rev).
Output:-
27
PROGRAM 7 : Program to append an integer into the list .
domains
x=integer
P list=integer*
a predicates
g append(x,list,list)
e
|
clauses
28 append(X,[],[X]).
append(X,[H|T],[H|T1]):-
append(X,T,T1).
Output:-
28
PROGRAM 8: Program to replace an integer from the list .
domains
list=integer*
P predicates
a replace(integer,integer,list,list)
g clauses
e
replace(X,Y,[X|T],[Y|T]).
|
29
replace(X,Y,[H|T],[H|T1]):-replace(X,Y,T,T1).
Output:-
29
PROGRAM 9 : Program to delete an integer from the list .
domains
list=integer*
predicates
P del(integer,list,list)
a clauses
g del(X,[X|T],T).
e del(X,[H|T],[H|T1]):-
| del(X,T,T1).
30
Output:-
30
PROGRAM 10 : Program to show concept of list.
domains
name=symbol*
P predicates
a itnames(name)
g clauses
e
itnames([ram,kapil,shweta]).
|
31 itnames([ram,shweta,kapil]).
Output:-
31
PROGRAM 11 : Program to demonstrate family relationship
predicates
parent(symbol,symbol)
P child(symbol,symbol)
a mother(symbol,symbol)
g
brother(symbol,symbol)
e
| sister(symbol,symbol)
32 grandparent(symbol,symbol)
male(symbol)
female(symbol)
clauses
parent(a,b).
sister(a,c).
male(a).
female(b).
child(X,Y):-parent(Y,X).
mother(X,Y):-female(X),parent(X,Y).
grandparent(X,Y):-parent(X,Z),parent(Z,Y).
brother(X,Y):-male(X),parent(V,X),parent(V,Y).
Output:-
32
PROGRAM 12 : Program to show how integer variable is used in prolog program
predicates
go
P clauses
a go:-X=10,
g write(X),
e nl,X=20,
| write(X),nl.
33
Output:-
33