0% found this document useful (0 votes)
188 views137 pages

Kaushal Chavda

This document provides information about an Artificial Intelligence lab manual for Computer Engineering students at L. D. College of Engineering in Ahmedabad, India. It lists the faculty members, course outcomes, rubric for assessment, and curriculum. The manual contains 13 experiments covering topics like search techniques, knowledge representation, game playing, natural language processing, and Prolog programming. It provides details of each experiment like the aim, date conducted, grade received, and faculty signature.

Uploaded by

All in one
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)
188 views137 pages

Kaushal Chavda

This document provides information about an Artificial Intelligence lab manual for Computer Engineering students at L. D. College of Engineering in Ahmedabad, India. It lists the faculty members, course outcomes, rubric for assessment, and curriculum. The manual contains 13 experiments covering topics like search techniques, knowledge representation, game playing, natural language processing, and Prolog programming. It provides details of each experiment like the aim, date conducted, grade received, and faculty signature.

Uploaded by

All in one
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/ 137

L. D.

College of Engineering
Opp Gujarat University, Navrangpura, Ahmedabad - 380015

LAB MANUAL
Branch: Computer Engineering

AI - ARTIFICIAL INTELLIGENCE (3170716)


Semester: VII

Faculty Details:
1) Prof. Bhavesh A. Oza

2) Prof. Hitesh Rajpoot


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Certificate

L. D. College of Engineering(computer department) 1


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Sr. CO AIM : AI Programs Date Page Grade Sign


No. No.

1 1,5 Study of PROLOG. 10/07/2021 8

2 1,2,3 Write a program to solve 8 queens’ problem 21/07/2021 18

3 1,2,3 Solve any problem using depth first search. 30/07/2021 23

4 1,3 Solve any problem using best first search. 03/08/2021 27

5 1,3 Solve 8-puzzle problem using best first search 13/08/2021 32

6 1,3 Solve Robot (traversal) problem using means 15/08/2021 37


End Analysis
7 1,3 Solve traveling salesman problem. 18/08/2021 41

8 1,3 Write a program to implement Tic-Tac-Toe 30/08/2021 44


game problem.
9 1,3 Write a program to implement BFS (for 8 04/09/2021 56
puzzle problem or Water Jug problem or any
AI search problem) .
10 1,3 Write a program to implement DFS (for 8 10/09/2021 61
puzzle problem or Water Jug problem or any
AI search problem)
11 1,3,4 Write a program to implement Single Player 16/09/2021 68
Game (Using Heuristic Function)
12 1,3,4 Write a program to Implement A* Algorithm. 23/09/2021 74

13 3,5 Write a program to solve N-Queens problem 08/10/2021 86


using Prolog.

L. D. College of Engineering(computer department) 2


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Sr. CO AIM : Prolog Programs Date Page Grade Sign


No. No.

1 1,5 Program to add two numbers. 10/07/2021 91

2 1,2,5 Program to categorize animal 21/07/2021 94


characteristics.
3 1,2,5 Program to read address of a person using 30/07/2021 97
compound variable.
4 1,2,5 Program of fun to show concept of cut 03/08/2021 101
operator.
5 1,4,5 Program to count number of elements in a 13/08/2021 104
list.
6 1,4,5 Program to reverse the list. 15/08/2021 107

7 1,4,5 Program to append an integer into the list. 18/08/2021 110

8 1,4,5 Program to replace an integer from the list. 30/08/2021 113

9 1,4,5 Program to delete an integer from the list. 04/09/2021 116

10 1,4,5 Program to show concept of list. 10/09/2021 119

11 1,4,5 Program to demonstrate family 16/09/2021 122


relationship.
12 1,4,5 Program to show how integer variable is 23/09/2021 126
used in prolog program.
13 1,5 Write the Conceptual Dependency for 08/10/2021 129
following statements.

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)

L. D. College of Engineering(computer department) 3


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

L. D. College of Engineering, Ahmedabad

Department of Computer Engineering


Subject Name: ARTICIFIAL INTELLIGENCE Subject Code: 3170716

Term: 2021-22

Rubrics ID Criteria Marks Good (2) Satisfactory Need


(1) Improvement
(0)

RB1 Regularity 05 High (>70%) Moderate (40- Poor (0-40%)


70%)

RB2 Problem 05 Apt & Full Limited Very Less


Analysis & Identification of Identification Identification of
Development of the Problem & of the Problem the Problem /
the Solution Complete / Incomplete Very Less
Solution for the Solution for Solution for the
Problem the Problem Problem

RB3 Testing of the 05 Correct Solution Partially Very less correct


Solution as required Correct solution for the
Solution for problem
the Problem

RB4 Mock viva test 05 All questions Delayed & Very few
responded partially questions
Correctly correct answered
response correctly

L. D. College of Engineering(computer department) 4


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

SIGN OF FACULTY

L. D. College of Engineering, Ahmedabad


Department of Computer Engineering
LABORATORY PRACTICALS ASSESSMENT
Subject Name: ARTICIFIAL INTELLIGENCE Subject Code: 3170716
Term: 2021-22
Enroll. No.:
Class:
Pract. CO RB1 RB2 RB3 RB4 Total Date Faculty Sign
No. No.

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

L. D. College of Engineering(computer department) 5


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD,


COURSE CURRICULUM
COURSE TITLE: ARTICIFIAL INTELLIGENCE (3170716)
(Code: 3170716)
Degree Programs in which this course is offered Semester in which offered

Computer Engineering 7th Semester

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:

Artificial Intelligence Techniques to solve the Complex engineering problems.

3. COURSE OUTCOMES

After learning the course, the students should be able to:


1. Demonstrate knowledge using search techniques, rules, expert systems, frames, semantic nets, and
predicate logic in order to solve complex problems based on the intelligent behavior of human-
centered problems
2. Examine the relationship among knowledge representation, uncertain information, probability
theory and logic by discussing statistical reasoning, with a focus on Bayes’ Theorem

L. D. College of Engineering(computer department) 6


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

4. TEACHING AND EXAMINATION SCHEME

5. SUGGESTED LEARNING RESOURCES


A. LIST OF BOOKS
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata McGraw-Hill
2. “Artificial Intelligence: A Modern Approach” -By Stuart Russel, Peter Norvig, PHI
3.“Introduction to Prolog Programming” -By Carl Townsend.
4. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)
5. “Programming with PROLOG” –By Klocksin and Mellish.
B. LIST OF SOFTWARE / LEARNING WEBSITES
 https://nptel.ac.in/courses/106/105/106105077/
 http://www.journals.elsevier.com/artificial-intelligence/

L. D. College of Engineering(computer department) 7


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 1

AIM: Study of PROLOG. Write the following programs using PROLOG.

 Objectives: Using Turbo Prolog


a. Basics of Turbo Prolog
b. Intro to Prolog programming
c. Running a simple program

 Theory:

 Prolog is a logical programming language and stands for PROgramming in


LOGic Created around 1972
 Preferred for AI programming and mainly used in such areas as: o
Theorem proving, expert systems, NLP, Logical programming is the use of
mathematical logic for computer programming.

 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

L. D. College of Engineering(computer department) 8


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

L. D. College of Engineering(computer department) 9


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Turbo Prolog/DOSBox + Prolog

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

 Delete line Ctrl-QF


 Search / Replace Ctrl-QA

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.

Trace:

 The Trace Panel is useful for finding problems in the programs you
create.
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.

Constants & Variables
Constants
 Constants are names that begin with lower case letters.
 Names of relationships are constants

Variables
 Variables take the place of constants in facts.
 Variables begin with upper case letters.

L. D. College of Engineering(computer department) 11


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Turbo Prolog Program

A Turbo Prolog program consists of two or more sections.

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.

L. D. College of Engineering(computer department) 12


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Steps:

What is a Prolog program?

Prolog is used for solving problems that involve objects and the relationships
between objects.

 A program consists of a database containing one or more facts and zero or


more rules.
 A fact is a relationship among a collection of objects. A fact is a oneline
statement that ends with a full-stop.
o parent (john, bart).
o parent (barbara, bart).
o male (john).
o dog(fido). >> Fido is a dog or It is true that fido is a dog
o sister(mary, joe). >> Mary is Joe’s sister.
o play(mary, joe, tennis). >> It is true that Mary and Joe play tennis.
Relationships can have any number of 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:

L. D. College of Engineering(computer department) 13


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

 Executing Simple Program


L. D. College of Engineering(computer department) 14
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

• Start Turbo Prolog


• Select the Edit mode
• Type in the program
• Exit the Editor using Esc.
• Save the program
• Select Run (which compiles the program for you in memory)
Once you have followed these steps you will see the following prompt in the Dialog
Panel:

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:

1. The goal will succeed; that is, it will be proven true.

2. The goal will fail; Turbo Prolog will not be able to match the goal with any facts in
the program.

3. The execution will fail because of an error 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

Goal: symptom(Disease, runny_nose).

Turbo Prolog will respond

L. D. College of Engineering(computer department) 15


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Disease = cold

Disease = flu 2 Solutions

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

 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:

L. D. College of Engineering(computer department) 17


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Signature of Faculty: Grade:

Practical – 2
AIM: Write a program to solve 8 queens problem

 Objectives: To understand the 8 queen problem and implement a program


for a solution to it.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount E E:\ (mounting the drive)
 E: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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.)

L. D. College of Engineering(computer department) 18


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 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:

domains

queen = q(integer, integer)


queens = queen*

freelist = integer*

board = board(queens, freelist, freelist, freelist, freelist)

predicates

nondeterm placeN(integer, board, board)


nondeterm place_a_queen(integer, board, board)

nondeterm nqueens(integer)

nondeterm makelist(integer, freelist)

nondeterm findandremove(integer, freelist, freelist)

nextrow(integer, freelist, freelist)

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

L. D. College of Engineering(computer department) 20


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Steps:

• STEP 1: Represent the board positions as 8*8 vector, i.e., [1, 2, 3, 4, 5, 6, 7,


8]. Store the set of queens in the list ‘Q’.
• STEP 2: Calculate the permutation of the above eight numbers stored in set
P.
• STEP 3: Let the position where the first queen to be placed be (1, Y), for
second be
• (2, Y1) and so on and store the positions in Q.
• STEP 4: Check for the safety of the queens through the predicate, ‘noattack
()’.

L. D. College of Engineering(computer department) 21


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

• 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:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 22


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 3
AIM: Solve any problem using depth first search

 Objectives: To understand the concept of Depth First Search (DFS) and


implement a program to solve any problem using the DFS strategy.

 Theory: Depth-first search (DFS) is an algorithm for traversing or searching


tree or graph data structures. The algorithm starts at the root node (selecting
some arbitrary node as the root node in the case of a graph) and explores as
far as possible along each branch before backtracking.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount E E:\ (mounting the drive)
 E: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written

L. D. College of Engineering(computer department) 23


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 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

L. D. College of Engineering(computer department) 24


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 to determine whether a node is child of other

Steps:

Domains
X=symbol Y=symbol*

Predicates

child(X,X)

childnode(X,X,Y)

path(X,X,Y)

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

L. D. College of Engineering(computer department) 25


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

Output:

Questions:

Signature of Faculty: Grade:


L. D. College of Engineering(computer department) 26
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 4
AIM: Solve any problem using best first search

 Objectives: To understand the concept of Breadth First Search (BFS) and


implement a program to solve any problem using the BFS strategy.

 Theory: 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 when the goal node very quickly finds its way to the front of the queue.
If this happens during Depth or Breadth first search, it will be a matter of luck
rather than design. To arrange for the goal node to be examined as soon as
possible, we can add the successors to the queue and then sort it with the aim
of placing the best successor, i.e. the successor that will lead soonest to the
goal, at the front of the queue.

This leads to a generalization 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.

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code

L. D. College of Engineering(computer department) 27


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 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>

using namespace std;

typedef pair<int, int> pi;

vector<vector<pi> > graph;

void addedge(int x, int y, int cost)

graph[x].push_back(make_pair(cost, y));

graph[y].push_back(make_pair(cost, x));

L. D. College of Engineering(computer department) 28


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

void best_first_search(int source, int target, int n)

vector<bool> visited(n, false);

priority_queue<pi, vector<pi>, greater<pi> > pq;

pq.push(make_pair(0, source));

int s = source;

visited[s] = true;

while (!pq.empty()) {

int x = pq.top().second;

cout << x << " ";

pq.pop();

if (x == target)

break;

for (int i = 0; i < graph[x].size(); i++) {

if (!visited[graph[x][i].second]) {

visited[graph[x][i].second] = true;

pq.push(make_pair(graph[x][i].first,graph[x][i].second));

L. D. College of Engineering(computer department) 29


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

addedge(8, 10, 6);

addedge(9, 11, 1);

addedge(9, 12, 10);

addedge(9, 13, 2);

L. D. College of Engineering(computer department) 30


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

int source = 0;

int target = 9;

best_first_search(source, target, v);

return 0;

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 31


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 5
AIM: Solve 8-puzzle problem using best first search

 Objectives: To understand the concept of 8-puzzle problem and implement a


program to find a solution to it.

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

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code

 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

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 '/')

L. D. College of Engineering(computer department) 32


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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:-

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

The 'move' productions are defined as follows.

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_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_fcn(A/B/C/D/E/F/G/H/I, S) -> 1 s_aux(A,B,S1), s_aux(B,C,S2), s_aux(C,F,S3),


s_aux(F,I,S4), s_aux(I,H,S5), s_aux(H,G,S6), s_aux(G,D,S7), s_aux(D,A,S8), s_aux(E,S9),

S is S1+S2+S3+S4+S5+S6+S7+S8+S9.

s_aux(0,0) -> cut


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

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

L. D. College of Engineering(computer department) 33


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

h_function(Puzz,H) :- p_fcn(Puzz,P), s_fcn(Puzz,S),


H is P + 3*S.

The 'move' predicate is defined as follows.

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

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.

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


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

%%% the out-of-cycle function

L. D. College of Engineering(computer department) 34


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

s_fcn(A/B/C/D/E/F/G/H/I, S) :-s_aux(A,B,S1), s_aux(B,C,S2), s_aux(C,F,S3),


s_aux(F,I,S4), s_aux(I,H,S5), s_aux(H,G,S6), s_aux(G,D,S7), s_aux(D,A,S8), s_aux(E,S9),

S is S1+S2+S3+S4+S5+S6+S7+S8+S9.

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

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:

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


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

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


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

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


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

L. D. College of Engineering(computer department) 35


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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


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

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


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

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 36


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 6
AIM: Solve Robot (traversal) problem using Means End Analysis

 Objectives: To understand the concept of Robot (traversal) problem and


implement a program to find a solution to it using the Means End Analysis
(MEA).

 Theory: Means-Ends Analysis is problem-solving techniques used in Artificial


intelligence for limiting search in AI programs.
o It is a mixture of Backward and forward search technique.
o The MEA technique was first introduced in 1961 by Allen Newell, and
Herbert A. Simon in their problem-solving computer program, which
was named as General Problem Solver (GPS).
o The MEA analysis process centered on the evaluation of the difference
between the current state and goal state.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)

L. D. College of Engineering(computer department) 37


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

o This will open a space where Prolog code can be written


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)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 Procedure: 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.

How means-ends analysis Works:

 The means-ends analysis process can be applied recursively for a problem. It


is a strategy to control search in problem-solving.
 Following are the main steps which describes the working of MEA technique
for solving a problem.
o First, evaluate the difference between Initial State and final State.

L. D. College of Engineering(computer department) 38


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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,Goals):Goals are in true State

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):Goal is add-list of action

achieves(Action,Goal):-
adds(Action,Goals),
member(Goal,Goals).

%apply(State,Action,NewState):Action executed in state produces NewState

L. D. College of Engineering(computer department) 39


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

apply(State,Action,NewState):-
deletes(Action,DelList),
delete_all(State,DelList,State1),!.
Adds(Action,AddList),
Conc(AddList,State1,NewState).

%delete_all(L1,L2,Diff) if Diff is set-difference of L1 and L2


delete_all([],_,[]).
delete_all([X|L1],L2,Diff):-
member(X,L2),!.
delete_all(L1,L2,Diff).
delete_all([X,L1],L2,[X|Diff]):-
delete_all(L1,L2,Diff).

%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:

Signature of Faculty: Grade

L. D. College of Engineering(computer department) 40


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 7
AIM: Solve traveling salesman problem

 Objectives: To understand the concept of Traveling Salesman Problem and


implement a program to find a solution to it.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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)

L. D. College of Engineering(computer department) 41


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 F9 (to compile the written program)


 Alt + R (to run the compiled program)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 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:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 43


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 8
AIM: Write a program to implement Tic-Tac-Toe game problem

 Objectives: To understand the concept of Tic-Tac-Toe game problem and


implement a program to find a solution to it.

 Theory: The game involves 2 players placing their respective symbols in a


3x3 grid. The player who manages to place three of their symbols in
horizontal/vertical/diagonal row wins the game. If either player fails to do so
the game ends in a draw. If both the people always play their optimal
strategies the game always ends in a draw.

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code

 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

 Ask the player 1 to enter a number from 1 to 9


 Suppose player 1 entered 5, then a symbol “X” will be inserted at
position 5 and player 2 will be asked to enter a number from the
remaining
 If user 2 enters 5, it will be considered as an invalid move and the
player will have to enter some other number
 If player 2 enters valid number, the other symbol “O” will be inserted
at the position of the number given by player 2
 This will continue till either of the player wins or the game goes draw
Steps:

#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
{

cout<<"\tTic Toc Toe Game"<<endl<<endl;


cout<<"Player 1 (X) || Player 2 (0)"<<endl;

cout << endl;


cout << " | | " << endl;
cout << " " << sq[1] << " | " << sq[2] << " | " << sq[3] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << sq[4] << " | " << sq[5] << " | " << sq[6] << endl;

L. D. College of Engineering(computer department) 45


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

cout << "_____|_____|_____" << endl;


cout << " | | " << endl;
cout << " " << sq[7] << " | " << sq[8] << " | " << sq[9] << endl;
cout << " | | " << endl << endl;

cout<<"(Player "<<player<<") Enter a number: ";


cin>>choice;

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;
}
}

if (sq[1] == sq[2] && sq[2] == sq[3])


win = 1;
else if (sq[4] == sq[5] && sq[5] == sq[6])
win = 1;
else if (sq[7] == sq[8] && sq[8] == sq[9])
win = 1;
else if (sq[1] == sq[4] && sq[4] == sq[7])
L. D. College of Engineering(computer department) 52
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

cout<<"\tTic Toc Toe Game"<<endl<<endl;


cout<<"Player 1 (X) || Player 2 (0)"<<endl;

cout << endl;


cout << " | | " << endl;
cout << " " << sq[1] << " | " << sq[2] << " | " << sq[3] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << sq[4] << " | " << sq[5] << " | " << sq[6] << endl;
cout << "_____|_____|_____" << endl;
cout << " | | " << endl;
cout << " " << sq[7] << " | " << sq[8] << " | " << sq[9] << endl;
cout << " | | " << endl << endl;

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:

L. D. College of Engineering(computer department) 54


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 55


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 9
AIM: Write a program to implement BFS (for 8 puzzle problem or Water Jug
problem or any AI search problem)

 Objectives: To understand the concept of water-jug problem and implement a


program to find a solution to it using Breadth First Search (BFS).

 Theory: Breadth-first search (BFS) is an algorithm for searching a tree data


structure for a node that satisfies a given property. It starts at the tree root
and explores all nodes at the present depth prior to moving on to the nodes at
the next depth level. Extra memory, usually a queue, is needed to keep track of
the child nodes that were encountered but not yet explored.

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

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code

L. D. College of Engineering(computer department) 56


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 Procedure: The problem is solvable only when t is a multiple of gcd(a, b) and


can be modeled as search through a state space. The state space for this
problem can be described as the set of ordered pair of integers (x, y) such that
x ∈ {0, 1, 2, …, a} and y ∈ {0, 1, 2, …, b}. The initial state is (0, 0) and the goal
states are (t, y) and (x, t) ∀ x, y.

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;

L. D. College of Engineering(computer department) 57


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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;

L. D. College of Engineering(computer department) 58


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

L. D. College of Engineering(computer department) 59


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

}
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:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 60


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 10
AIM: Write a program to implement DFS (for 8 puzzle problem or Water Jug
problem or any AI search problem)

 Objectives: To understand the concept of water-jug problem and implement a


program to find a solution to it using Depth First Search (DFS).

 Theory: Depth-first search is a recursive algorithm for traversing a tree or


graph data structure. It is called the depth-first search because it starts from
the root node and follows each path to its greatest depth node before moving
to the next path. DFS uses a stack data structure for its implementation.

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code

 Procedure: The problem is solvable only when t is a multiple of gcd(a, b) and


can be modeled as search through a state space. The state space for this
problem can be described as the set of ordered pair of integers (x, y) such that
x ∈ {0, 1, 2, …, a} and y ∈ {0, 1, 2, …, b}. The initial state is (0, 0) and the goal
states are (t, y) and (x, t) ∀ x, y.
L. D. College of Engineering(computer department) 61
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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;

bool operator < (const state& that) const {

L. D. College of Engineering(computer department) 62


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

if (x != that.x) return x < that.x;


return y < that.y;
}
};
int capacity_x, capacity_y, target;

void dfs(state start, stack <pair <state, int> >& path) {


stack <state> s;
state goal = (state) {-1, -1};
map <state, pair <state, int> > parentOf;

s.push(start);
parentOf[start] = make_pair(start, 0);

while (!s.empty()) {
state top = s.top();
s.pop();

if (top.x == target || top.y == target) {


goal = top;
break;
}
if (top.x < capacity_x) {
state child = (state) {capacity_x, top.y};
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
parentOf[child] = make_pair(top, 1);
}
}
if (top.y < capacity_y) {
state child = (state) {top.x, capacity_y};
if (parentOf.find(child) == parentOf.end()) {
s.push(child);

L. D. College of Engineering(computer department) 63


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

parentOf[child] = make_pair(top, 2);


}
}
if (top.x > 0) {
state child = (state) {0, top.y};
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
parentOf[child] = make_pair(top, 3);
}
}
if (top.y > 0) {
state child = (state) {top.x, 0};
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
parentOf[child] = make_pair(top, 4);
}
}
if (top.y > 0) {
state child = (state) {min(top.x + top.y, capacity_x), max(0, top.x + top.y -
capacity_x)};
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
parentOf[child] = make_pair(top, 5);
}
}
if (top.x > 0) {
state child = (state) {max(0, top.x + top.y - capacity_y), min(top.x + top.y,
capacity_y)};
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
parentOf[child] = make_pair(top, 6);
}
}

L. D. College of Engineering(computer department) 64


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

}
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;

printf("Enter the capacities of the two jugs : ");


scanf("%d %d", &capacity_x, &capacity_y);
printf("Enter the target amount : ");
scanf("%d", &target);

dfs((state) {0, 0}, path);


if (path.empty())
printf("\nTarget cannot be reached.\n");
else {
printf("\nNumber of moves to reach the target : %d\nOne path to the
target is as follows :\n", path.size() - 1);
while (!path.empty()) {
state top = path.top().first;
int rule = path.top().second;
path.pop();

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

L. D. College of Engineering(computer department) 65


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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;
}

L. D. College of Engineering(computer department) 66


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 67


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 11
AIM: Write a program to implement Single Player Game (Using Heuristic
Function)

 Objectives: To understand the concept of “Heuristic Function” and implement


a program for a “Single Player Game” using that concept.

 Theory: Heuristic is a function which is used in Informed Search, and it finds


the most promising path. It takes the current state of the agent as its input and
produces the estimation of how close agent is from the goal. The heuristic
method, however, might not always give the best solution, but it guaranteed to
find a good solution in reasonable time. Heuristic function estimates how
close a state is to the goal. It is represented by h(n), and it calculates the cost
of an optimal path between the pair of states. The value of the heuristic
function is always positive.

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code

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

 In the next step, user’s symbol will be shown at the previously


mentioned coordinates and the computer will also have made its move
 Take next coordinates from user
 The process keeps repeating till either of user or computer wins or the
game goes draw
 In any step, if the user gives invalid coordinates as input, the game
terminates

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;

for(i=0; i<3; i++)


for(j=0; j<3; j++)
matrix[i][j] = ' ';
}
void get_player_move(void)
{
int x, y;
printf("Enter X,Y coordinates for your move: "); scanf("%d%*c%d", &x, &y);
x--; y--;
if(matrix[x][y]!= ' '){
printf("Invalid move, try again.\n");
get_player_move();
}
else
matrix[x][y] = 'X';
}
void get_computer_move(void)
{
int i, j;
for(i=0; i<3; i++){

L. D. College of Engineering(computer department) 70


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

for(j=0; j<3; j++)


if(matrix[i][j]==' ')
break;
if(matrix[i][j]==' ')
break;

}
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];

L. D. College of Engineering(computer department) 71


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

if(matrix[0][0]==matrix[1][1] && matrix[1][1]==matrix[2][2])


return matrix[0][0];
if(matrix[0][2]==matrix[1][1] && matrix[1][1]==matrix[2][0])
return matrix[0][2];
return ' ';
}
Output:

L. D. College of Engineering(computer department) 72


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 73


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 12
AIM: Write a program to Implement A* Algorithm

 Objectives: To understand the concept of A* algorithm and implement a


program to find a solution of a path searching problem using A* algorithm.

 Theory: A* search is the most commonly known form of best-first search. It


uses heuristic function h(n), and cost to reach the node n from the start state
g(n). It has combined features of UCS and greedy best-first search, by which it
solve the problem efficiently. A* search algorithm finds the shortest path
through the search space using the heuristic function. This search algorithm
expands less search tree and provides optimal result faster. A* algorithm is
similar to UCS except that it uses g(n)+h(n) instead of g(n). In A* search
algorithm, we use search heuristic as well as the cost to reach the node. Hence
we can combine both costs as following, and this sum is called as a fitness
number.
o f(n) = g(n) + h(n)

 Background / Preparation: Download and install CodeBlocks or VS Code.


o Install all the necessary extensions for compilation and execution of the
code if using VS Code

 Tools / Material Needed:


o Hardware: Laptop
o Software: CodeBlocks/VS Code
L. D. College of Engineering(computer department) 74
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

3. while the open list is not empty


a) find the node with the least f on the open list, call it "q"
b) pop q off the open list
c) generate q's 8 successors and set their
parents to q
d) for each successor
i) if successor is the goal, stop search
successor.g = q.g + distance between successor and q
successor.h = distance from goal to successor (This can be done using
many ways, we will discuss three heuristics - Manhattan, Diagonal and
Euclidean Heuristics)

successor.f = successor.g + successor.h

ii) if a node with the same position as


successor is in the OPEN list which has a
lower f than successor, skip this successor

iii) if a node with the same position as


successor is in the CLOSED list which has
a lower f than successor, skip this successor
otherwise, add the node to the open list
end (for loop)

e) push q on the closed list


end (while loop)

L. D. College of Engineering(computer department) 75


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Steps:

#include <bits/stdc++.h>
using namespace std;

#define ROW 9
#define COL 10
typedef pair<int, int> Pair;

typedef pair<double, pair<int, int> > pPair;

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(

L. D. College of Engineering(computer department) 76


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

(row - dest.first) * (row - dest.first)


+ (col - dest.second) * (col - dest.second)));
}
void tracePath(cell cellDetails[][COL], Pair dest)
{
printf("\nThe Path is ");
int row = dest.first;
int col = dest.second;

stack<Pair> Path;

while (!(cellDetails[row][col].parent_i == row


&& cellDetails[row][col].parent_j == col)) {
Path.push(make_pair(row, col));
int temp_row = cellDetails[row][col].parent_i;
int temp_col = cellDetails[row][col].parent_j;
row = temp_row;
col = temp_col;
}

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;
}

L. D. College of Engineering(computer department) 77


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

if (isUnBlocked(grid, src.first, src.second) == false


|| isUnBlocked(grid, dest.first, dest.second)
== false) {
printf("Source or the destination is blocked\n");
return;
}
if (isDestination(src.first, src.second, dest)
== true) {
printf("We are already at the destination\n");
return;
}
bool closedList[ROW][COL];
memset(closedList, false, sizeof(closedList));
cell cellDetails[ROW][COL];

int i, j;

for (i = 0; i < ROW; i++) {


for (j = 0; j < COL; j++) {
cellDetails[i][j].f = FLT_MAX;
cellDetails[i][j].g = FLT_MAX;
cellDetails[i][j].h = FLT_MAX;
cellDetails[i][j].parent_i = -1;
cellDetails[i][j].parent_j = -1;
}
}
i = src.first, j = src.second;
cellDetails[i][j].f = 0.0;
cellDetails[i][j].g = 0.0;
cellDetails[i][j].h = 0.0;
cellDetails[i][j].parent_i = i;
cellDetails[i][j].parent_j = j;
set<pPair> openList;
openList.insert(make_pair(0.0, make_pair(i, j)));
bool foundDest = false;

while (!openList.empty()) {
pPair p = *openList.begin();
openList.erase(openList.begin());

L. D. College of Engineering(computer department) 78


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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;

L. D. College of Engineering(computer department) 79


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

}
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)));

L. D. College of Engineering(computer department) 80


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

cellDetails[i][j + 1].f = fNew;


cellDetails[i][j + 1].g = gNew;
cellDetails[i][j + 1].h = hNew;
cellDetails[i][j + 1].parent_i = i;
cellDetails[i][j + 1].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)));
cellDetails[i][j - 1].f = fNew;
cellDetails[i][j - 1].g = gNew;
cellDetails[i][j - 1].h = hNew;
cellDetails[i][j - 1].parent_i = i;
cellDetails[i][j - 1].parent_j = j;
}
}
}
if (isValid(i - 1, j + 1) == true) {
if (isDestination(i - 1, j + 1, dest) == true) {
cellDetails[i - 1][j + 1].parent_i = i;
cellDetails[i - 1][j + 1].parent_j = j;

L. D. College of Engineering(computer department) 81


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

printf("The destination cell is found\n");


tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i - 1][j + 1] == false
&& isUnBlocked(grid, i - 1, j + 1)
== true) {
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i - 1, j + 1, dest);
fNew = gNew + hNew;
if (cellDetails[i - 1][j + 1].f == FLT_MAX
|| cellDetails[i - 1][j + 1].f > fNew) {
openList.insert(make_pair(
fNew, make_pair(i - 1, j + 1)));
cellDetails[i - 1][j + 1].f = fNew;
cellDetails[i - 1][j + 1].g = gNew;
cellDetails[i - 1][j + 1].h = hNew;
cellDetails[i - 1][j + 1].parent_i = i;
cellDetails[i - 1][j + 1].parent_j = j;
}
}
}
if (isValid(i - 1, j - 1) == true) {
if (isDestination(i - 1, j - 1, dest) == true) {
cellDetails[i - 1][j - 1].parent_i = i;
cellDetails[i - 1][j - 1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i - 1][j - 1] == false
&& isUnBlocked(grid, i - 1, j - 1)
== true) {
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i - 1, j - 1, dest);
fNew = gNew + hNew;
if (cellDetails[i - 1][j - 1].f == FLT_MAX

L. D. College of Engineering(computer department) 82


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

|| cellDetails[i - 1][j - 1].f > fNew) {


openList.insert(make_pair(
fNew, make_pair(i - 1, j - 1)));
cellDetails[i - 1][j - 1].f = fNew;
cellDetails[i - 1][j - 1].g = gNew;
cellDetails[i - 1][j - 1].h = hNew;
cellDetails[i - 1][j - 1].parent_i = i;
cellDetails[i - 1][j - 1].parent_j = j;
}
}
}
if (isValid(i + 1, j + 1) == true) {
if (isDestination(i + 1, j + 1, dest) == true) {
cellDetails[i + 1][j + 1].parent_i = i;
cellDetails[i + 1][j + 1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i + 1][j + 1] == false
&& isUnBlocked(grid, i + 1, j + 1)
== true) {
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i + 1, j + 1, dest);
fNew = gNew + hNew;
if (cellDetails[i + 1][j + 1].f == FLT_MAX
|| cellDetails[i + 1][j + 1].f > fNew) {
openList.insert(make_pair(
fNew, make_pair(i + 1, j + 1)));
cellDetails[i + 1][j + 1].f = fNew;
cellDetails[i + 1][j + 1].g = gNew;
cellDetails[i + 1][j + 1].h = hNew;
cellDetails[i + 1][j + 1].parent_i = i;
cellDetails[i + 1][j + 1].parent_j = j;
}
}
}
if (isValid(i + 1, j - 1) == true) {

L. D. College of Engineering(computer department) 83


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

if (isDestination(i + 1, j - 1, dest) == true) {


cellDetails[i + 1][j - 1].parent_i = i;
cellDetails[i + 1][j - 1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
else if (closedList[i + 1][j - 1] == false
&& isUnBlocked(grid, i + 1, j - 1)
== true) {
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i + 1, j - 1, dest);
fNew = gNew + hNew;
if (cellDetails[i + 1][j - 1].f == FLT_MAX
|| cellDetails[i + 1][j - 1].f > fNew) {
openList.insert(make_pair(
fNew, make_pair(i + 1, j - 1)));
cellDetails[i + 1][j - 1].f = fNew;
cellDetails[i + 1][j - 1].g = gNew;
cellDetails[i + 1][j - 1].h = hNew;
cellDetails[i + 1][j - 1].parent_i = i;
cellDetails[i + 1][j - 1].parent_j = j;
}
}
}
}
if (foundDest == false)
printf("Failed to find the Destination Cell\n");

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 },

L. D. College of Engineering(computer department) 84


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

{ 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);

aStarSearch(grid, src, dest);

return (0);
}
Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 85


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Practical – 13
AIM: Write a program to solve N-Queens problem using Prolog

 Objectives: To understand the N-Queen problem and implement a prolog


program to find a solution to it.

 Theory: N - Queens problem is to place n - queens in such a manner on an n x


n chessboard that no queens attack each other by being in the same row,
column or diagonal. For n =1, the problem has a trivial solution, and no
solution exists for n =2 and n =3. So first we consider the 4 queens problem
and then generate it to n - queen problem.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written

L. D. College of Engineering(computer department) 86


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 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

L. D. College of Engineering(computer department) 87


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Steps:

domains

queen = q(integer, integer)

queens = queen*

freelist = integer*

board = board(queens, freelist, freelist, freelist, freelist)

predicates

nondeterm placeN(integer, board, board)

nondeterm place_a_queen(integer, board, board)

nondeterm nqueens(integer)

nondeterm makelist(integer, freelist)

nondeterm findandremove(integer, freelist, freelist)

nextrow(integer, freelist, freelist)

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

L. D. College of Engineering(computer department) 89


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 90


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written

L. D. College of Engineering(computer department) 91


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 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),

L. D. College of Engineering(computer department) 92


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

write("enter second number "),


readint(Y),
Z=X+Y,
write(“sum of “,X,” and ”,Y,” is ”,Z).
Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 93


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 2
AIM: Program to categorize animal characteristics

 Objectives: To divide animals according to their categories like small, big,


their color, etc.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:

L. D. College of Engineering(computer department) 94


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

L. D. College of Engineering(computer department) 95


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

clauses
small(rat).
small(cat).
large(lion).
color(dog,black).
color(rabbit,white).
color(X,dark):-
color(X,black);
color(X,brown).
Output:

Questions:

Signature of Faculty: Grade:


L. D. College of Engineering(computer department) 96
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written

L. D. College of Engineering(computer department) 97


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

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

L. D. College of Engineering(computer department) 98


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

L. D. College of Engineering(computer department) 99


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 100


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 4
AIM: Program of fun to show concept of cut operator

 Objectives: to understand the concept of cut operator with a fun program in


prolog.

 Theory: Here, a program is written which checks the goal, compares it with
the condition in clauses and returns the output “yes” or “no”.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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)

L. D. College of Engineering(computer department) 101


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 Alt + R (to run the compiled program)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 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,!.

L. D. College of Engineering(computer department) 102


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 103


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 5
AIM: Program to count number of elements in a list

 Objectives: To understand the concept of counting the number of elements


from a list taken as an input from the user.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:

L. D. College of Engineering(computer department) 104


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 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:
 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.

L. D. College of Engineering(computer department) 105


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

L. D. College of Engineering(computer department) 106


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Signature of Faculty: Grade:

Program – 6
AIM: Program to reverse the list

 Objectives: To understand the concept of reversing of elements of a list taken


as an input from the user.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written

L. D. College of Engineering(computer department) 107


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

 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:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 109


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 7
AIM: Program to append an integer into the list

 Objectives: To understand the concept of appending an element to a list of


elements taken as an input from the user.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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)

L. D. College of Engineering(computer department) 110


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 F9 (to compile the written program)


 Alt + R (to run the compiled program)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

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

L. D. College of Engineering(computer department) 111


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 112


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 8
AIM: Program to replace an integer from the list

 Objectives: To understand the concept of replacing an element in a list of


elements taken as an input from the user.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:

L. D. College of Engineering(computer department) 113


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 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:
 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).

L. D. College of Engineering(computer department) 114


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 115


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 9
AIM: Program to delete an integer from the list

 Objectives: To understand the concept of deleting an element from a list of


elements taken as an input from the user.

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

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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)

L. D. College of Engineering(computer department) 116


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 F9 (to compile the written program)


 Alt + R (to run the compiled program)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

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

L. D. College of Engineering(computer department) 117


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 118


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 10
AIM: Program to show concept of list

 Objectives: To understand the concept of list by implementing it in prolog.

 Theory: A list in Prolog is a collection of terms, which is useful for grouping


items together, or for dealing with large volumes of related data, etc. Lists are
enclosed by square brackets, and items are separated by commas. The length
of a list is the number of items it contains.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
o Here, only keyboard shortcuts can be used to operate. The most needed
shortcuts are:

L. D. College of Engineering(computer department) 119


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 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:
 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]).

L. D. College of Engineering(computer department) 120


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 121


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 11
AIM: Program to demonstrate family relationship

 Objectives: To understand the defining of relationship in prolog and using it


to check relationships.

 Theory: Here, various relationships like parent, child, grandparent, mother,


sister, brother, male, and female are defined along with some values to show
who has what relationship with who. The user can enter a random pair to
check if they share a particular relationship.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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.)

L. D. College of Engineering(computer department) 122


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 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:
 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)

L. D. College of Engineering(computer department) 123


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

L. D. College of Engineering(computer department) 124


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 125


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 12
AIM: Program to show how integer variable is used in prolog program

 Objectives: To understand the usage of integer variable which is used in a


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.

 Background / Preparation: To setup DOSBox in order to execute the Prolog


Programs,
o Download zipped Prolog-main folder from
https://github.com/priyam001/Prolog
o Download DOSBox from https://sourceforge.net/projects/dosbox/
o Extract the Prolog-main file, rename it as Prolog and copy it in the
desired drive (I have chosen F: drive)
o Run the DOSBox installer and complete the installation process
o Open DOSBox and run the following commands
 Mount F F:\ (mounting the drive)
 F: (drive where Prolog folder is stored)
 cd Prolog (to enter the Prolog folder)
 Prolog.exe (to run the executable file)
o This will open a space where Prolog code can be written
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)

L. D. College of Engineering(computer department) 126


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

 F9 (to compile the written program)


 Alt + R (to run the compiled program)

 Tools / Material Needed:


o Hardware: Laptop
o Software: Prolog, DOSBox

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

L. D. College of Engineering(computer department) 127


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Output:

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 128


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Program – 13
AIM: Write the Conceptual Dependency for following statements.

(a) John gives Mary a book

(b) John gave Mary the book yesterday

 Objectives: To understand the given statements and write “Conceptual


Dependency” for the same using the rules.

 Theory: Conceptual Dependency originally developed to represent


knowledge acquired from natural language input.
 The goals of this theory are:
o To help in the drawing of inference from sentences.
o To be independent of the words used in the original input.
o That is to say: For any 2 (or more) sentences that are identical in
meaning there should be only one representation of that meaning.

Examples of Primitive Acts are:


ATRANS - Transfer of an abstract relationship. e.g. give.
PTRANS - Transfer of the physical location of an object. e.g. go.
PROPEL - Application of a physical force to an object. e.g. push.
MTRANS - Transfer of mental information. e.g. tell.
MBUILD - Construct new information from old. e.g. decide.
SPEAK - Utter a sound. e.g. say.
ATTEND - Focus a sense on a stimulus. e.g. listen, watch.
MOVE - Movement of a body part by owner. e.g. punch, kick.
GRASP - Actor grasping an object. e.g. clutch.
INGEST - Actor ingesting an object. e.g. eat.
EXPEL - Actor getting rid of an object from body. e.g. ????.

L. D. College of Engineering(computer department) 129


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Six primitive conceptual categories provide building blocks which are the set
of allowable dependencies in the concepts in a sentence:

PP - Real world objects.


ACT - Real world actions.
PA - Attributes of objects.
AA - Attributes of actions.
T - Times.
LOC - Locations.

 Background / Preparation: To understand the concept of “Conceptual


Dependency”

 Tools / Material Needed:


o Hardware: None
o Software: None

 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

L. D. College of Engineering(computer department) 130


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

Steps:

Mary (to)
P O R
John ATRANS book

John (from)

Mary (to)
yesterday P O R
John ATRANS book

John (from)

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 131


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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.

 Theory: Semantic networks are alternative of predicate logic for knowledge


representation. In Semantic networks, we can represent our knowledge in the
form of graphical networks. This network consists of nodes representing
objects and arcs which describe the relationship between those objects.
Semantic networks can categorize the object in different forms and can also
link those objects. Semantic networks are easy to understand and can be
easily extended.

L. D. College of Engineering(computer department) 132


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

This representation consist of mainly two types of relations:

1. IS-A relation (Inheritance)


2. Kind-of-relation

 Background / Preparation: To understand the concept of “Semantic Net”


and how it is built.

 Tools / Material Needed:


o Hardware: None
o Software: None

 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

L. D. College of Engineering(computer department) 133


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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:

o Tom is a cat is represented by Cat(Tom)


o The cat sat on the mat is represented by
∃x∃y(Cat(x)∧Mat(y)∧SatOn(x,y))
o A cat is a mammal is represented by ∀x(Cat(X)→Mammal(x))

We can clean up the representation by distinguishing between nodes representing


individual or instances, and nodes representing classes. The is_a link will only be
used to show an individual belonging to a class. The link representing one class
being a subset of another will be labelled a_kind_of, or ako for short. The names
instance and subclass are often used in the place of is_a and ako.
Note also the modification which causes the link labelled is_owned_by to be
reversed in direction. This is in order to avoid links representing passive
relationships. In general a passive sentence can be replaced by an active one, so
“Tom is owned by John” becomes “John owns Tom”. In general, the rule which
converts passive to active in English converts sentences of the form “X is Yed by Z”
to “Z Ys X”. This is just an example (though often used for illustration) of the much
more general principle of looking beyond the immediate surface structure of a
sentence to find its deep structure.

L. D. College of Engineering(computer department) 134


ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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,

“Tom caught a bird” would be represented in logic by ∃x(bird(x)∧caught(Tom,x)),

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

A direct Prolog representation can be used, with classes represented by predicates,


thus:
L. D. College of Engineering(computer department) 135
ARTICIFIAL INTELLIGENCE (3170716) kaushal chavda(180280107021)

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

So, in general, an is_a link between a class c and an individual m is represented by


the fact c(m).

An a_kind_of link between a subclass c and a superclass s is represented by s(X) :-


c(X). If a property p with further arguments a1, … ,an is held by all members of a
class c, it is represented by p(X,a1,…,an) :- c(X). If a property p with further
arguments a1, … ,an is specified as held by an individual m, rather than a class to
which m belongs, it is represented by p(m,a1,…,an).

Questions:

Signature of Faculty: Grade:

L. D. College of Engineering(computer department) 136

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy