Kaushal Chavda
Kaushal Chavda
College of Engineering
Opp Gujarat University, Navrangpura, Ahmedabad - 380015
LAB MANUAL
Branch: Computer Engineering
Faculty Details:
1) Prof. Bhavesh A. Oza
Certificate
cat(tom). cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger)
Term: 2021-22
RB4 Mock viva test 05 All questions Delayed & Very few
responded partially questions
Correctly correct answered
response correctly
SIGN OF FACULTY
1 1,5
2 1,2,3
3 1,2,3
4 1,3
5 1,3
6 1,3
7 1,3
8 1,3
9 1,3
10 1,3
11 1,3,4
12 1,3,4
13 3,5
1. RATIONALE
• With the usage of Internet and World Wide Web increasing day by day, the field of AI and
its techniques are being used in many areas which directly affect human life.
• Various techniques for encoding knowledge in computer systems such as Predicate Logic,
Production rules, Semantic networks find application in real world problems.
• The fields of AI such as Game Playing, Natural Language Processing and Connectionist
Models are also important.
• Student should know some programming language for AI.
2. COMPETENCY
The course content should be taught and analyze with the aim to develop different types of
skills so that students are able to acquire following competency:
3. COURSE OUTCOMES
3. Develop intelligent algorithms for constraint satisfaction problems and also design intelligent
systems for Game Playing
4. Make a use of natural language processing and connectionist models of neural networks to AI
domain
5. Develop the capability to represent various real life problem domains using logic-based techniques
and use this to perform inference using prolog programming language
Practical – 1
Theory:
Background / Preparation:
To start Turbo Prolog, open a MSDOS window and type: N> prolog
followed by a carriage return.
Below is the command setup and interface of DOSBox
Procedure:
The GUI:
GUI is composed of four panels and a main menu bar.
The menu bar lists six options – Files, Edit, Run, Compile, Options, Setup.
The four panels are Editor, Dialog, Message and Trace.
MENU
Files – Enables the user to load programs from disk, create new
programs, save modified programs to disk, and to quit the program.
Edit – Moves user control to the Editor panel.
Run – Moves user control to the Dialog panel ; compiles the user
program (if not already done so) in memory before running the
program.
Compile – Provides the user with choices on how to save the compiled
version of the program.
Options – Provides the user with choices on the type of compilation to
be used.
Setup – Enables the user to change panel sizes, colors, and positions.
Editor:
Simple to use editor with support for common Command editing tasks.
Function left arrow/right arrow
Character left/right Ctrl-left arrow/Ctrl-right arrow
Word left/right up arrow/down arrow
Line up/down PgUp/PgDn
Page up/down Home/End
Beginning/End of line Backspace/Delete
Delete character Ctrl-Y
L. D. College of Engineering(computer department) 10
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
Trace:
The Trace Panel is useful for finding problems in the programs you
create.
Prolog Clauses:
Variables
Variables take the place of constants in facts.
Variables begin with upper case letters.
Clauses Section
The main body of the prolog program.
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).
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.
Steps:
Prolog is used for solving problems that involve objects and the relationships
between objects.
Choose names that are meaningful – because in Prolog names are arbitrary strings
but people will have to associate meaning to them.
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.
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.
3. The arguments of a predicate can either be names of objects (constants) or
variables.
4. When defining relationships between objects using facts, attention should be
paid to the order in which the objects are listed. While programming the order
is arbitrary, however the programmer must decide on some order and be
consistent.
5. Ex. likes(tom, anna). >> The relationship defined has a different meaning if the
order of the objects is changed. Here the first object is understood to be the
“liker”. If we wanted to state that Anna also likes Tom then we would have to
add to our database – likes(anna, tom).
6. Remember that we must determine how to interpret the names of objects and
relationships.
Sample Program:
Domains
disease,indication = symbol
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).
Goal: Using a Prolog program is essentially about asking questions. To ask the
executing Prolog program a question you specify the Goal.
Turbo Prolog will respond with True and prompt for another goal. Possible
outcomes of specifying a goal:
2. The goal will fail; Turbo Prolog will not be able to match the goal with any facts in
the program.
Execution is a matching process. The program attempts to match the goal with one
of the clauses in the clauses section beginning with the first clause. If it does find a
complete match, the goal succeeds and True is 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 – type in
Disease = cold
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:
True
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 instantiated
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.
Program to demonstrate a simple prolog program.
Predicates
like(symbol,symbol)
L. D. College of Engineering(computer department) 16
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
hate(symbol,symbol)
Clauses
like(sita,ram).
like(x,y).
like(a,b).
hate(c,d).
hate(m,n).
hate(f,g).
Questions:
Practical – 2
AIM: Write a program to solve 8 queens problem
Theory: The eight queen problem is the problem of placing eight queens on
an 8×8 chessboard such that none of them attack one another (no two are in
the same row, column, or diagonal). More generally, the n queen problem
places n queens on an n × n chessboard.
Procedure:
domains
freelist = integer*
predicates
nondeterm nqueens(integer)
clauses
nqueens(N):-
L. D. College of Engineering(computer department) 19
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
makelist(N,L),Diagonal=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,NewC),
D1=N+C-R,findandremove(D1,Diag1,NewD1),
D2=R+C-1,findandremove(D2,Diag2,NewD2).
findandremove(X,[X|Rest],Rest).
findandremove(X,[Y|Rest],[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:
Steps:
• 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.
Questions:
Practical – 3
AIM: Solve any problem using depth first search
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
X and Y
Define the predicates
child
childnode
path
Define the clauses
b is a child of a
c is a child of a
d is a child of a
e is a child of b
f is a child of b
g is a child of c
to find the path from root to leaf
Steps:
Domains
X=symbol Y=symbol*
Predicates
child(X,X)
childnode(X,X,Y)
path(X,X,Y)
clauses
childnode(A,G,Z).
childnode(A,G,[X|L]):-
child(A,X),
childnode(X,G,L).
Output:
Questions:
Practical – 4
AIM: Solve any problem using best first search
Procedure:
We start from source "S" and search for goal "I" using given costs and
Best First search.
pq initially contains S
We remove s from and process unvisited neighbors of S to pq.
pq now contains {A, C, B} (C is put before B because C has lesser cost)
We remove A from pq and process unvisited neighbors of A to pq.
pq now contains {C, B, E, D}
We remove C from pq and process unvisited neighbors of C to pq.
pq now contains {B, H, E, D}
We remove B from pq and process unvisited neighbors of B to pq.
pq now contains {H, E, D, F, G}
We remove H from pq. Since our goal
"I" is a neighbor of H, we return.
Steps:
#include <bits/stdc++.h>
graph[x].push_back(make_pair(cost, y));
graph[y].push_back(make_pair(cost, x));
pq.push(make_pair(0, source));
int s = source;
visited[s] = true;
while (!pq.empty()) {
int x = pq.top().second;
pq.pop();
if (x == target)
break;
if (!visited[graph[x][i].second]) {
visited[graph[x][i].second] = true;
pq.push(make_pair(graph[x][i].first,graph[x][i].second));
int main()
int v = 14;
graph.resize(v);
addedge(0, 1, 3);
addedge(0, 2, 6);
addedge(0, 3, 5);
addedge(1, 4, 9);
addedge(1, 5, 8);
addedge(2, 6, 12);
addedge(2, 7, 14);
addedge(3, 8, 7);
addedge(8, 9, 5);
int source = 0;
int target = 9;
return 0;
Output:
Questions:
Practical – 5
AIM: Solve 8-puzzle problem using best first search
Theory: Given a 3×3 board with 8 tiles (every tile has one number from 1 to
8) and one empty space. The objective is to place the numbers on tiles to
match the final configuration using the empty space. We can slide four
adjacent (left, right, above, and below) tiles into the empty space.
Procedure: The most frequent older versions of this puzzle have numbers or
letters and 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 illustration, we use the 3 x 3 8-tile version, which is depicted here in goal
configuration
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).
Steps:
Production Rules:-
P is Pa+Pb+Pc+Pd+Pe+Pf+Pg+Ph+Pg+Pi.
S is S1+S2+S3+S4+S5+S6+S7+S8+S9.
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).
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).
P is Pa+Pb+Pc+Pd+Pe+Pf+Pg+Ph+Pg+Pi.
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).
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).
Solution:
Questions:
Practical – 6
AIM: Solve Robot (traversal) problem using Means End Analysis
o Select the various operators which can be applied for each difference.
o Apply the operator at each difference, which reduces the difference
between the current state and goal state.
Steps:
%plan(State,Goals,Plan,FinalState)
%The way plan is decomposed into stages by conc, the precondition plan (Preplan)
is found in breadth-first fashion. However the length of the rest of the plan is not
restricted and goals are achieved in depth-first style
plan(State,Goals,Plan,FinalState):-
conc(Preplan,[Action|Postplan],Plan), %Divide plan
select(state,Goals,Goal), %Select goal
achieves(Action,Goal), %Relevant Action
can(Action,Condition),
plan(State,Condition,Preplan,Midstate1), %Enable action
apply(MidState1,Action,Midstate2), %Apply action
plan(MidState2,Goals,Postplan,FinalState). %Achieve remaining goals
satisfied(State,[Goal|Goals]):-
member(Goal,State),
satisfied(State,Goals).
Select(State,Goals,Goal):-
Member(Goal,Goals),
Not member(Goal,State). %Goal not satisfied already
achieves(Action,Goal):-
adds(Action,Goals),
member(Goal,Goals).
apply(State,Action,NewState):-
deletes(Action,DelList),
delete_all(State,DelList,State1),!.
Adds(Action,AddList),
Conc(AddList,State1,NewState).
%member function
member(X,[X|Tail]).
member(X,[Head|Tail]):-
member(X,Tail).
%Concatenation function
conc([],L,L).
conc([X|L1],L2,[X|L3]):-
conc(L1,L2,L3).
Questions:
Practical – 7
AIM: Solve traveling salesman problem
Theory: Given a set of cities and distance between every pair of cities, the
problem is to find the shortest possible route that visits every city exactly
once and returns to the starting point.
Procedure:
Define the domains
Town
Distance
Define the predicates
nondeterm road
nondeterm route
Define the clauses with values
road
route
distance
Steps:
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
L. D. College of Engineering(computer department) 42
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
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,!.
Questions:
Practical – 8
AIM: Write a program to implement Tic-Tac-Toe game problem
Procedure:
Display a 3x3 block with numbers 1 to 9
1 2 3
L. D. College of Engineering(computer department) 44
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
4 5 6
7 8 9
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char sq[10] = {'o','1','2','3','4','5','6','7','8','9'};
int player = 1;
int choice;
int win = -1;
do
{
if(player == 1)
{
switch(choice)
{
case 1:
if(sq[1]=='X'||sq[1]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[1] = 'X';
player = 2;
}
break;
case 2:
if(sq[2]=='X'||sq[2]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[2] = 'X';
player = 2;
}
break;
L. D. College of Engineering(computer department) 46
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
case 3:
if(sq[3]=='X'||sq[3]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[3] = 'X';
player = 2;
}
break;
case 4:
if(sq[4]=='X'||sq[4]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[4] = 'X';
player = 2;
}
break;
case 5:
if(sq[5]=='X'||sq[5]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[5] = 'X';
player = 2;
}
break;
L. D. College of Engineering(computer department) 47
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
case 6:
if(sq[6]=='X'||sq[6]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[6] = 'X';
player = 2;
}
break;
case 7:
if(sq[7]=='X'||sq[7]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[7] = 'X';
player = 2;
}
break;
case 8:
if(sq[8]=='X'||sq[8]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[8] = 'X';
player = 2;
}
break;
case 9:
L. D. College of Engineering(computer department) 48
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
if(sq[9]=='X'||sq[9]=='O')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[9] = 'X';
player = 2;
}
break;
default:cout<<"Invalid Move"<<endl;
system("pause");
break;
}
}
else
{
switch(choice)
{
case 1:
if(sq[1]=='O'||sq[1]=='X')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[1] = 'O';
player = 1;
}
break;
case 2:
if(sq[2]=='O'||sq[2]=='X')
{
L. D. College of Engineering(computer department) 49
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[2] = 'O';
player = 1;
}
break;
case 3:
if(sq[3]=='O'||sq[3]=='X')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[3] = 'O';
player = 1;
}
break;
case 4:
if(sq[4]=='O'||sq[4]=='X')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[4] = 'O';
player = 1;
}
break;
case 5:
if(sq[5]=='O'||sq[5]=='X')
{
L. D. College of Engineering(computer department) 50
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[5] = 'O';
player = 1;
}
break;
case 6:
if(sq[6]=='O'||sq[6]=='X')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[6] = 'O';
player = 1;
}
break;
case 7:
if(sq[7]=='O'||sq[7]=='X')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[7] = 'O';
player = 1;
}
break;
case 8:
if(sq[8]=='O'||sq[8]=='X')
{
cout<<"Invalid Move"<<endl;
L. D. College of Engineering(computer department) 51
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
system("pause");
}
else
{
sq[8] = 'O';
player = 1;
}
break;
case 9:
if(sq[9]=='O'||sq[9]=='X')
{
cout<<"Invalid Move"<<endl;
system("pause");
}
else
{
sq[9] = 'O';
player = 1;
}
break;
default:cout<<"Invalid Move"<<endl;
system("pause");
break;
}
}
win = 1;
else if (sq[2] == sq[5] && sq[5] == sq[8])
win = 1;
else if (sq[3] == sq[6] && sq[6] == sq[9])
win = 1;
else if (sq[1] == sq[5] && sq[5] == sq[9])
win = 1;
else if (sq[3] == sq[5] && sq[5] == sq[7])
win = 1;
else if (sq[1] != '1' && sq[2] != '2' && sq[3] != '3' && sq[4] != '4' &&
sq[5] != '5' && sq[6] != '6' && sq[7] != '7' && sq[8] != '8' && sq[9] != '9')
win = 0;
else
win = -1;
system("cls");
}
while(win == -1);
if(win==1)
{
if(player == 1)
{
L. D. College of Engineering(computer department) 53
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
player = 2;
}
else if(player == 2)
{
player = 1;
}
cout<<"\aPlayer "<<player<<" win "<<endl;
}
else
cout<<"\aGame draw"<<endl;
return 0;
}
Output:
Questions:
Practical – 9
AIM: Write a program to implement BFS (for 8 puzzle problem or Water Jug
problem or any AI search problem)
The Water Jug problem can be stated as follows: “Given two unmarked jugs having
capacities ‘a’ and ‘b’ liters respectively and a target volume ‘t’ liters, find the moves
that get exactly ‘t’ liters in any of the two jugs.”
All we need now for a search procedure to work is a way to generate new states
(successors) from a given state. This is captured by production rules that specify
how and when a new state can be generated from a given state. For the water jug
problem, the following production rules are sufficient:
1 (x, y) -> (a, y) if x < a i.e., Fill the first jug if it is not already full
2 (x, y) -> (x, b) if y < b i.e., Fill the second jug if it is not already full
3 (x, y) -> (0, y) if x > 0 i.e., Empty the first jug
4 (x, y) -> (x, 0) if y > 0 i.e, Empty the second jug
5 (x, y) -> (min(x + y, a), max(0, x + y – a)) if y > 0 i.e., Pour from second jug
into first jug until the first jug is full or the second jug is empty
6 (x, y) -> (max(0, x + y – b), min(x + y, b)) if x > 0 i.e., Pour from first jug into
second jug until the second jug is full or the first jug is empty
Strictly speaking, the conditions in the production rules are not required e.g., we
could fill an already full jug except that it won’t lead us anywhere and would be
wasteful in a tree search procedure where the visited states are not saved to
prevent revisiting.
Now, a search procedure like BFS or DFS can be applied to systematically search
from the initial state to one of the goal states through the state space.
Steps:
#include <bits/stdc++.h>
using namespace std;
class nodes{
public:
pair<int,int> p;
int first;
int second;
string s;
};
string makestring(int a,int b){
std::stringstream out1;
std::stringstream out2;
string t1,t2,str;
out1 << a;
t1 = out1.str();
out2 << b;
t2 = out2.str();
str = "("+t1+","+t2+")";
return str;
}
int main()
{
int counter = 0;
ios::sync_with_stdio(false);
nodes cap,ini,final;
ini.p.first=0,ini.p.second=0;
ini.s = makestring(ini.p.first,ini.p.second);
cout<<"Enter the capacity of 2 jugs\n";
cin>>cap.p.first>>cap.p.second;
cout<<"Enter the required jug config\n";
cin>>final.p.first>>final.p.second;
queue<nodes> q;
q.push(ini);
nodes jug;
while(!q.empty()){
jug = q.front();
if(jug.p.first == final.p.first){
cout<<jug.s<<endl;
return 0;
}
nodes temp = jug;
if(jug.p.first<cap.p.first){
temp.p = make_pair(cap.p.first,jug.p.second);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.second<cap.p.second){
temp.p = make_pair(jug.p.first,cap.p.second);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.first>0){
temp.p = make_pair(0,jug.p.second);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.second>0){
temp.p = make_pair(jug.p.first,0);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.first>0 && (jug.p.first+jug.p.second)>=cap.p.second){
temp.p = make_pair((jug.p.first-(cap.p.second-
jug.p.second)),cap.p.second);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.second>0 && (jug.p.first+jug.p.second)>=cap.p.first){
temp.p = make_pair(cap.p.first,(jug.p.second-(cap.p.first-jug.p.first)));
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.first>0 && (jug.p.first+jug.p.second)<=cap.p.second){
temp.p = make_pair(0,jug.p.first+jug.p.second);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
if(jug.p.second>0 && (jug.p.first+jug.p.second)<=cap.p.first){
temp.p = make_pair(jug.p.first+jug.p.second,0);
temp.s = jug.s + makestring(temp.p.first,temp.p.second);
q.push(temp);
}
q.pop();
}
return 0;
}
Output:
Questions:
Practical – 10
AIM: Write a program to implement DFS (for 8 puzzle problem or Water Jug
problem or any AI search problem)
All we need now for a search procedure to work is a way to generate new states
(successors) from a given state. This is captured by production rules that specify
how and when a new state can be generated from a given state. For the water jug
problem, the following production rules are sufficient:
7 (x, y) -> (a, y) if x < a i.e., Fill the first jug if it is not already full
8 (x, y) -> (x, b) if y < b i.e., Fill the second jug if it is not already full
9 (x, y) -> (0, y) if x > 0 i.e., Empty the first jug
10 (x, y) -> (x, 0) if y > 0 i.e, Empty the second jug
11 (x, y) -> (min(x + y, a), max(0, x + y – a)) if y > 0 i.e., Pour from second jug
into first jug until the first jug is full or the second jug is empty
12 (x, y) -> (max(0, x + y – b), min(x + y, b)) if x > 0 i.e., Pour from first jug into
second jug until the second jug is full or the first jug is empty
Strictly speaking, the conditions in the production rules are not required e.g., we
could fill an already full jug except that it won’t lead us anywhere and would be
wasteful in a tree search procedure where the visited states are not saved to
prevent revisiting.
Now, a search procedure like BFS or DFS can be applied to systematically search
from the initial state to one of the goal states through the state space.
Steps:
#include <cstdio>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;
struct state {
int x, y;
s.push(start);
parentOf[start] = make_pair(start, 0);
while (!s.empty()) {
state top = s.top();
s.pop();
}
if (goal.x == -1 || goal.y == -1)
return;
path.push(make_pair(goal, 0));
while (parentOf[path.top().first].second != 0)
path.push(parentOf[path.top().first]);
}
int main() {
stack <pair <state, int> > path;
switch (rule) {
case 0: printf("State : (%d, %d)\n#\n", top.x, top.y);
break;
case 1: printf("State : (%d, %d)\nAction : Fill the first jug\n", top.x,
top.y);
break;
case 2: printf("State : (%d, %d)\nAction : Fill the second jug\n", top.x,
top.y);
break;
case 3: printf("State : (%d, %d)\nAction : Empty the first jug\n", top.x,
top.y);
break;
case 4: printf("State : (%d, %d)\nAction : Empty the second jug\n",
top.x, top.y);
break;
case 5: printf("State : (%d, %d)\nAction : Pour from second jug into
first jug\n", top.x, top.y);
break;
case 6: printf("State : (%d, %d)\nAction : Pour from first jug into
second jug\n", top.x, top.y);
break;
}
}
}
return 0;
}
Output:
Questions:
Practical – 11
AIM: Write a program to implement Single Player Game (Using Heuristic
Function)
Procedure:
For playing Tic-Tac-Toe, take input coordinates of the block where the
user wants to place his/her symbol
L. D. College of Engineering(computer department) 68
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
Steps:
#include <stdio.h>
#include <stdlib.h>
char matrix[3][3]; char check(void);
void init_matrix(void);
void get_player_move(void);
void get_computer_move(void);
void disp_matrix(void);
int main(void)
{
char done;
printf("Tic Tac Toe\n");
printf("This is a 'Single Player Game'\nYou will be playing against the
computer\n");
done = ' ';
init_matrix();
do {
disp_matrix();
get_player_move();
done = check();
if(done!= ' ')
break;
get_computer_move();
L. D. College of Engineering(computer department) 69
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
done = check();
} while(done== ' ');
if(done=='X')
printf("You won!\n");
else
printf("I won!!!!\n");
disp_matrix();
return 0;
}
void init_matrix(void)
{
int i, j;
}
if(i*j==9) {
printf("draw\n");
exit(0);
}
else
matrix[i][j] = 'O';
}
void disp_matrix(void)
{
int t;
for(t=0; t<3; t++) {
printf(" %c | %c | %c ",matrix[t][0],matrix[t][1], matrix [t][2]);
if(t!=2)
printf("\n---|---|---\n");
}
printf("\n");
}
char check(void)
{
int i;
for(i=0; i<3; i++)
if(matrix[i][0]==matrix[i][1] && matrix[i][0]==matrix[i][2])
return matrix[i][0];
if(matrix[0][i]==matrix[1][i] && matrix[0][i]==matrix[2][i])
return matrix[0][i];
Questions:
Practical – 12
AIM: Write a program to Implement A* Algorithm
Procedure:
1. Initialize the open list
2. Initialize the closed list
put the starting node on the open
list (you can leave its f at zero)
Steps:
#include <bits/stdc++.h>
using namespace std;
#define ROW 9
#define COL 10
typedef pair<int, int> Pair;
struct cell {
int parent_i, parent_j;
double f, g, h;
};
bool isValid(int row, int col)
{
return (row >= 0) && (row < ROW) && (col >= 0)
&& (col < COL);
}
bool isUnBlocked(int grid[][COL], int row, int col)
{
if (grid[row][col] == 1)
return (true);
else
return (false);
}
bool isDestination(int row, int col, Pair dest)
{
if (row == dest.first && col == dest.second)
return (true);
else
return (false);
}
double calculateHValue(int row, int col, Pair dest)
{
return ((double)sqrt(
stack<Pair> Path;
Path.push(make_pair(row, col));
while (!Path.empty()) {
pair<int, int> p = Path.top();
Path.pop();
printf("-> (%d,%d) ", p.first, p.second);
}
return;
}
void aStarSearch(int grid[][COL], Pair src, Pair dest)
{
if (isValid(src.first, src.second) == false) {
printf("Source is invalid\n");
return;
}
if (isValid(dest.first, dest.second) == false) {
printf("Destination is invalid\n");
return;
}
int i, j;
while (!openList.empty()) {
pPair p = *openList.begin();
openList.erase(openList.begin());
i = p.second.first;
j = p.second.second;
closedList[i][j] = true;
double gNew, hNew, fNew;
if (isValid(i - 1, j) == true) {
if (isDestination(i - 1, j, dest) == true) {
cellDetails[i - 1][j].parent_i = i;
cellDetails[i - 1][j].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i - 1][j] == false
&& isUnBlocked(grid, i - 1, j)
== true) {
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue(i - 1, j, dest);
fNew = gNew + hNew;
if (cellDetails[i - 1][j].f == FLT_MAX
|| cellDetails[i - 1][j].f > fNew) {
openList.insert(make_pair(
fNew, make_pair(i - 1, j)));
cellDetails[i - 1][j].f = fNew;
cellDetails[i - 1][j].g = gNew;
cellDetails[i - 1][j].h = hNew;
cellDetails[i - 1][j].parent_i = i;
cellDetails[i - 1][j].parent_j = j;
}
}
}
if (isValid(i + 1, j) == true) {
if (isDestination(i + 1, j, dest) == true) {
cellDetails[i + 1][j].parent_i = i;
cellDetails[i + 1][j].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i + 1][j] == false
&& isUnBlocked(grid, i + 1, j)
== true) {
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue(i + 1, j, dest);
fNew = gNew + hNew;
if (cellDetails[i + 1][j].f == FLT_MAX
|| cellDetails[i + 1][j].f > fNew) {
openList.insert(make_pair(
fNew, make_pair(i + 1, j)));
// Update the details of this cell
cellDetails[i + 1][j].f = fNew;
cellDetails[i + 1][j].g = gNew;
cellDetails[i + 1][j].h = hNew;
cellDetails[i + 1][j].parent_i = i;
cellDetails[i + 1][j].parent_j = j;
}
}
}
if (isValid(i, j + 1) == true) {
if (isDestination(i, j + 1, dest) == true) {
cellDetails[i][j + 1].parent_i = i;
cellDetails[i][j + 1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i][j + 1] == false
&& isUnBlocked(grid, i, j + 1)
== true) {
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue(i, j + 1, dest);
fNew = gNew + hNew;
if (cellDetails[i][j + 1].f == FLT_MAX
|| cellDetails[i][j + 1].f > fNew) {
openList.insert(make_pair(
fNew, make_pair(i, j + 1)));
return;
}
int main()
{
int grid[ROW][COL]
= { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } };
Pair src = make_pair(8, 0);
Pair dest = make_pair(0, 0);
return (0);
}
Output:
Questions:
Practical – 13
AIM: Write a program to solve N-Queens problem using Prolog
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
queen
queens
freelist
board
Define the predicates
nondeterm placeN
nondeterm place_a_queen
nondeterm nqueens
nondeterm makelist
nondeterm findandremove
nextrow
Define the clauses
Using the defined domains and predicates, define the clauses
(methodology) to arrange the “N” number of queens on the board
according to the rules
N is the input (number of queens) taken from the user
Steps:
domains
queens = queen*
freelist = integer*
predicates
nondeterm nqueens(integer)
clauses
nqueens(N):-
makelist(N,L),Diagonal=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):-
L. D. College of Engineering(computer department) 88
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
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,NewC),
D1=N+C-R,findandremove(D1,Diag1,NewD1),
D2=R+C-1,findandremove(D2,Diag2,NewD2).
findandremove(X,[X|Rest],Rest).
findandremove(X,[Y|Rest],[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:
Questions:
Prolog Programs
Program – 1
AIM: Program to add two numbers
Objectives: To take 2 numbers from user, add them and display the result in
the dialog box.
Theory: Here, in order to add two numbers, input is taken from the user as
number 1 and number 2 and then by using the declared predicate “add”, the
output obtained by the addition of the given two numbers is displayed in the
dialog box.
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Declare the predicates
add
Declare the clauses
Take input of first number from user
Read number 1
Take input of second number from user
Read number 2
Add
Display output
Steps:
predicates
add
clauses
add:-
write("enter first number "),
readint(X),
Questions:
Program – 2
AIM: Program to categorize animal characteristics
Theory: Here, the user defines the categories and defines some animals
thereby categorizing them according to the defined categories which includes
sizes like small, large, etc. and other attributes like color, etc.
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Tools / Material Needed:
o Hardware: Laptop
o Software: Prolog, DOSBox
Procedure:
Declare the predicates
small
large
color
Declare the clauses
Define according to categories
rat is a small animal
cat is a small animal
lion is a large animal
dog has black color
rabbit has white color
dark color means black or brown
Run to fetch output
small(X) gives X = rat and X = cat as defined in the clauses
Steps:
predicates
small(symbol)
large(symbol)
color(symbol,symbol)
clauses
small(rat).
small(cat).
large(lion).
color(dog,black).
color(rabbit,white).
color(X,dark):-
color(X,black);
color(X,brown).
Output:
Questions:
Program – 3
AIM: Program to read address of a person using compound variable
Objectives: To define a compound variable and read address of the user and
display it in the dialog box.
Theory: Here, the user is asked his/her name and after entering that, he/she
is asked to enter address in parts like street, city, state, zip, etc. The user is
then asked whether the given input should be accepted or not (confirmation).
The user can choose “y” for yes and “n” for no. On pressing y, the entered
address is displayed in the dialog box along with the name of the user.
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
person
name
street
city
state
zip
Define the predicates
Readaddress
go
Define the clauses
The clauses use domains and predicates to take the input from the
user, read it, and display the same in the dialog box
Steps:
domains
person=address(name,street,city,state,zip)
name,street,city,state,zip=String
predicates
read_add(person)
go
clauses
go:-
read_add(Address),nl,
write(Address),nl,nl,
write("Accept(y/n)?"),readchar(R),
R='y',!.
go:-
nl,nl,write("please re-enter"),nl,go.
read_add(address(N,S,C,T,Z)):-
write("Name: "), readln(N),
write("Street: "), readln(S),
write("City: "), readln(C),
write("State: "), readln(T),
write("Zip: "), readln(Z).
Output:
Questions:
Program – 4
AIM: Program of fun to show concept of cut operator
Theory: Here, a program is written which checks the goal, compares it with
the condition in clauses and returns the output “yes” or “no”.
Procedure:
Define the predicates
fun (which takes 2 integers as value)
Define the clauses
If a value “Y” is less than 3, fun reutrns (Y,1)
If a value “Y” is from 4 to 10, fun returns (Y,2)
If a value “Y” is greater than 10, fun returns (Y,3)
Steps:
predicates
fun(integer,integer)
clauses
fun(Y,1):-Y<3,!.
fun(Y,2):-Y>3,Y<=10,!.
fun(Y,3):-Y>10,!.
Output:
Questions:
Program – 5
AIM: Program to count number of elements in a list
Theory: Here, the user is supposed to provide an input in the form of a list
and by comparing that with the defined clauses, the elements in the list are
counted and the result is displayed in the dialog box.
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
x (which is an integer)
list (which accepts input in the form of a list from the user)
Define the predicates
count (to store the counted value of the number of elements)
Define the clauses
conditions for reading the input given by the user and counting
the number of elements to display as a result
Steps:
domains
x=integer list=integer*
predicates
count(list,x)
clauses
count([],0).
count([_|T],N):-
count(T,N1),N=N1+1.
Output:
Questions:
Program – 6
AIM: Program to reverse the list
Theory: Here, the user is supposed to provide an input in the form of a list
and by comparing that with the defined clauses, the elements in the list are
reversed and the result is displayed in the dialog box.
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
x (which is an integer)
list (which accepts input in the form of a list from the user)
Define the predicates
append
rev
Define the clauses
conditions for reading the input given by the user and reversing
the elements to display as a result
Steps:
domains
x=integer list=integer*
predicates
append(x,list,list)
rev(list,list)
clauses
append(X,[],[X]).
L. D. College of Engineering(computer department) 108
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)
append(X,[H|T],[H|T1]):-
append(X,T,T1).
rev([],[]).
rev([H|T],T2):-
rev(T,L),
append(H,L,T2).
Output:
Questions:
Program – 7
AIM: Program to append an integer into the list
Theory: Here, the user is supposed to provide an input in the form of a list
and by comparing that with the defined clauses, the new element (provided by
the user) is appended to the list and the result is displayed in the dialog box.
Procedure:
Define the domains
x (which is an integer)
list (which accepts input in the form of a list from the user)
Define the predicates
append
Define the clauses
conditions for reading the input given by the user and appending
an element to the list of elements to display as a result
Steps:
Domains
x=integer list=integer*
predicates
append(x,list,list)
clauses
append(X,[],[X]).
append(X,[H|T],[H|T1]):-
append(X,T,T1).
Output:
Questions:
Program – 8
AIM: Program to replace an integer from the list
Theory: Here, the user is supposed to provide an input in the form of a list
and by comparing that with the defined clauses, an element is replaced in the
list and the result is displayed in the dialog box.
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
list (which accepts input in the form of a list from the user)
Define the predicates
replace
Define the clauses
conditions for reading the input given by the user and replacing
an element in the list of elements to display as a result
Steps:
domains
list=integer*
predicates
replace(integer,integer,list,list)
clauses
replace(X,Y,[X|T],[Y|T]).
replace(X,Y,[H|T],[H|T1]):-
replace(X,Y,T,T1).
Output:
Questions:
Program – 9
AIM: Program to delete an integer from the list
Theory: Here, the user is supposed to provide an input in the form of a list
and by comparing that with the defined clauses, an element is deleted from
the list and the result is displayed in the dialog box.
Procedure:
Define the domains
list (which accepts input in the form of a list from the user)
Define the predicates
del
Define the clauses
conditions for reading the input given by the user and deleting an
element from the list of elements to display as a result
Steps:
Domains
list=integer*
predicates
del(integer, list, list)
clauses
del(X,[X|T],T).
del(X,[H|T],[H|T1]):-
del(X,T,T1).
Output:
Questions:
Program – 10
AIM: Program to show concept of list
Alt + F (opens file dropdown menu where we can see options like
“New File”, “Save As”, Quit”, etc.)
Alt + E (to edit written program)
F9 (to compile the written program)
Alt + R (to run the compiled program)
Procedure:
Define the domains
name
Define the predicates
itnames
Define the clauses
Using predicates to add elements into the list
Steps:
domains
name=symbol*
predicates
itnames(name)
clauses
itnames([xyz,abc,pqr]).
itnames([xyz,pqr,abc]).
Output:
Questions:
Program – 11
AIM: Program to demonstrate family relationship
Procedure:
Define the predicates
parent
child
mother
brother
sister
grandparent
male
female
Define the clauses
clauses are defined by giving values to the defined predicates
Steps:
predicates
parent(symbol,symbol)
child(symbol,symbol)
mother(symbol,symbol)
brother(symbol,symbol)
sister(symbol,symbol)
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:
Questions:
Program – 12
AIM: Program to show how integer variable is used in prolog program
Theory: Here, integer variables are declared and assigned a value and when
the goal is given, the clauses are checked and the answer “yes” or “no” is
displayed accordingly in the dialog box.
Procedure:
Define the predicates
go
Define the clauses
X=10
X=20
Steps:
Predicates
go
clauses
go:-
X=10,
write(X),
nl,X=20,
write(X),nl.
Output:
Questions:
Program – 13
AIM: Write the Conceptual Dependency for following statements.
Six primitive conceptual categories provide building blocks which are the set
of allowable dependencies in the concepts in a sentence:
Procedure:
Identify the componenets in the statement
Identify the “building blocks” and “acts” to be used to represent the
statements
Apply the rules of “conceptual dependency” for both the given
statements
Use ATRANS for “give”
Here, from is “John”
Similarly, to is “Mary”
Use the rule of time for “yesterday” in the second statement
Steps:
Mary (to)
P O R
John ATRANS book
John (from)
Mary (to)
yesterday P O R
John ATRANS book
John (from)
Questions:
Program – 14
AIM: Convert following Prolog predicates into Semantic Net
o cat(tom). cat(cat1).
o mat(mat1).
o sat_on(cat1,mat1).
o bird(bird1).
o caught(tom,bird1).
o like(X,cream) :– cat(X).
o mammal(X) :– cat(X).
o has(X,fur) :– mammal(X).
o animal(X) :– mammal(X).
o animal(X) :– bird(X).
o owns(john,tom).
o is_coloured(tom,ginger)
Objectives: The idea is that we can store our knowledge in the form of a
graph, with nodes representing objects in the world, and arcs representing
relationships between those objects.
Procedure:
It is argued that this form of representation is closer to the way human structure
knowledge by building mental links between things than the predicate logic we
considered earlier. Note in particular how all the information about a particular
object is concentrated on the node representing that object, rather than scattered
around several clauses in logic.
There is, however, some confusion here which stems from the imprecise nature of
semantic nets. A particular problem is that we haven’t distinguished between nodes
representing classes of things, and nodes representing individual objects.
So, for example, the node labelled Cat represents both the single (nameless) cat who
sat on the mat, and the whole class of cats to which Tom belongs, which are
mammals and which like cream. The is_a link has two different meanings – it can
mean that one object is an individual item from a class, for example Tom is a
member of the class of cats, or that one class is a subset of another, for example, the
class of cats is a subset of the class of mammals. This confusion does not occur in
logic, where the use of quantifiers, names and predicates makes it clear what we
mean so:
Steps:
Note that where we had an unnamed member of some class, we have had to
introduce a node with an invented name to represent a particular member of the
class. For example,
which would be Skolemised by replacing the x with a Skolem constant; the same
thing was done above where bird1 was the name given to the individual bird that
Tom caught.
There are still plenty of issues to be resolved if we really want to represent what is
meant by the English phrases, or to be really clear about what the semantic net
means, but we are getting towards a notation that can be used practically (one
example of a thing we have skated over is how to deal with mass nouns like “fur” or
“cream” which refer to things that come in amounts rather than individual objects).
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
Questions: