Parth AI
Parth AI
Chandkheda, Ahmedabad
                  Affiliated
              Laboratory Manual
                        Of
              Artificial Intelligence
                    (3170716)
                B.E. Semester 7
             (Computer Engineering)
                 Submitted By:
                  Parth Rajput
                (190640107029)
This is to certify that Rajput Parth Bearing Hall Ticket No. 190640107029
student of Computer Engineering 7th Semester has Completed Artificial
Intelligence Lab Record work (3170716) during the year 2022-2023.
INDEX
Practical                                              Page
No.                          AIM                                 Date       Sign
                                                       No.
                                                                             1|Page
ARTIFICIAL INTELLIGENCE (3170716)                                         190640107029
PRACTICAL – 1
problem. Program:-
#include <stdio.h>
#include <ctype.h>
char square[10] = { 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int checkwin();
void board();
int main()
int player = 1, i,
do
board();
player = (player % 2) ? 1 : 2;
scanf("%d", &choice);
square[1] = mark;
square[2] = mark;
                                                                            2|Page
ARTIFICIAL INTELLIGENCE (3170716)           190640107029
else if (choice == 3 && square[3] == '3')
square[3] = mark;
square[4] = mark;
square[5] = mark;
square[6] = mark;
square[7] = mark;
square[8] = mark;
square[9] = mark;
else
printf("Invalid move
"); player--;
i=
checkwin();
player++;
}while (i == - 1);
board();
if (i == 1)
                                      4|Page
ARTIFICIAL INTELLIGENCE (3170716)                                       190640107029
else
printf("==>\aGame draw");
return 0;
int checkwin()
return 1;
return 1;
return 1;
return 1;
return 1;
return 1;
return 1;
return 1;
else if (square[1] != '1' && square[2] != '2' && square[3] != '3' &&
square[4] != '4' && square[5] != '5' && square[6] != '6' && square[7]
                                                                          5|Page
ARTIFICIAL INTELLIGENCE (3170716)                              190640107029
return 0;
else
return -
1;
void board()
printf(" | | \n");
printf(" | | \n");
printf(" | | \n");
printf(" | | \n");
printf(" | | \n");
printf(" | | \n\n");
                                                                 6|Page
ARTIFICIAL INTELLIGENCE (3170716)                                 190640107029
PRACTICAL – 2
AIM:- Write a program to implement BFS (for 8 puzzle problem or Water Jug
problemor any AI search problem).
Program :-
#include<stdio.h>
#include<ctype.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v) {
for (i=1;i<=n;i++)
q[++r]=i;
if(f<=r)
{ visited[q[f]]=
1;
bfs(q[f++]);
int main()
{int v;
vertices:");scanf("%d",&n);
for (i=1;i<=n;i++)
{q[i]=0;
visited[i]=0;
                                                                     7|Page
ARTIFICIAL INTELLIGENCE (3170716)               190640107029
}
n");for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
scanf("%d",&v);
bfs(v);
n");for (i=1;i<=n;i++)
if(visited[i]) printf("%d\
t",i); else
return 0;
                                                  8|Page
ARTIFICIAL INTELLIGENCE (3170716)                                 190640107029
PRACTICAL - 3
AIM:- Write a program to implement DFS (for 8 puzzle problem or Water Jug
problem or any AI search problem).
Program:-
#include <cstdio>
#include <stack>
#include <map>
#include <algorithm>
using namespace
int x, y;
};
{stack <state> s;
s.push(start);
                                                                    9|Page
ARTIFICIAL INTELLIGENCE (3170716)                                            190640107029
parentOf[start] = make_pair(start, 0);
while (!s.empty()) {
s.pop();
{goal =
top; break;
// Consider this state for visiting only if it has not been visited before
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
if (parentOf.find(child) == parentOf.end())
{s.push(child);
if (top.x > 0) {
                                                                               10 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                      190640107029
if (parentOf.find(child) == parentOf.end())
{s.push(child);
if (top.y > 0) {
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
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);
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);
}
                                                                                          11 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                190640107029
return;
path.push(make_pair(goal, 0));
while (parentOf[path.top().first].second != 0)
path.push(parentOf[path.top().first]);
int main() {
scanf("%d", &capacity_x);
scanf("%d", &capacity_y);
");scanf("%d", &target);
path); if
(path.empty())
n");else {
printf("\nNumber of moves to reach the target : %d\nOne path to the target is as follows
while (!path.empty())
                                      13 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                    190640107029
switch (rule) {
break;
case 1: printf("State : (%d, %d)\nAction : Fill the first jug\n", top.x, top.y);
break;
case 2: printf("State : (%d, %d)\nAction : Fill the second jug\n", top.x, top.y);
break;
case 3: printf("State : (%d, %d)\nAction : Empty the first jug\n", top.x, top.y);
break;
case 4: printf("State : (%d, %d)\nAction : Empty the second jug\n", top.x, top.y);
break;
case 5: printf("State : (%d, %d)\nAction : Pour from second jug into first jug\n", top.x,
top.y);
break;
case 6: printf("State : (%d, %d)\nAction : Pour from first jug into second jug\n", top.x,
top.y);
break;
return 0;
                                                                                        14 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                         190640107029
PRACTICAL - 4
Program :-
#include <stdio.h>
char gridChar(int i)
{switch(i) {
case -1:
return 'X';
case 0:
return ' ';
case 1:
return 'O';
}
return 0;
printf(" %c | %c | %c\
n",gridChar(b[0]),gridChar(b[1]),gridChar(b[2])); printf("---+---+---\
n");
printf(" %c | %c | %c\
n",gridChar(b[3]),gridChar(b[4]),gridChar(b[5])); printf("---+---+---\
n");
printf(" %c | %c | %c\n",gridChar(b[6]),gridChar(b[7]),gridChar(b[8]));
}
int i;
                                                                                             16 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                              190640107029
for(i = 0; i < 8; ++i)
{ if(board[wins[i][0]] != 0 &&
board[wins[i][0]] == board[wins[i][1]] &&
board[wins[i][0]] == board[wins[i][2]])
return board[wins[i][2]];
}
return 0;
                                                                 17 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                    190640107029
{int move = -1;
int score = -2;
int i;
int tempScore;
for(i = 0; i < 9; ++i)
{if(board[i] == 0)
{ board[i] = 1;
tempScore = -minimax(board, -
1); board[i] = 0;
if(tempScore > score)
{score = tempScore;
move = i;
}
}
}
//returns a score based on minimax tree at a given
node.board[move] = 1;
}
while (move >= 9 || move < 0 && board[move] == 0);
board[move] = -1;
int main() {
switch(win(board))
{case 0:
printf("A draw. How droll.\n");
break;
case 1:
draw(board);
printf("You lose.\n");
break;
case -1:
printf("You win.\n");
break;
}
return 0;
}
                                                          19 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                            190640107029
PRACTICAL-5
Program :-
import java.util.*;
public class AStar
{
  public static final int DIAGONAL_COST = 14;
  public static final int V_H_COST = 10;
  static class Cell{
     int heuristicCost = 0; //Heuristic cost
     int finalCost = 0; //G+H
     int i, j;
     Cell parent;
     Cell(int i, int j)
     {
        this.i = i;
        this.j = j;
     }
      @Override
     public String toString(){
        return "["+this.i+", "+this.j+"]";
      }
}
                                                21 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                   190640107029
       endJ = j;
 }
static void checkAndUpdateCost(Cell current, Cell t, int
       cost){if(t == null || closed[t.i][t.j])return;
       int t_final_cost =
       t.heuristicCost+cost; boolean inOpen
       = open.contains(t); if(!inOpen ||
       t_final_cost<t.finalCost){
   t.finalCost = t_final_cost;
          t.parent = current;
        if(!inOpen)open.add(t);
        }
    }
        list.open.add(grid[startI][startJ]);
        Cell current;
        while(true){
         current = open.poll();
            if(current==null)break;
            closed[current.i][current.j]=true;
            if(current.equals(grid[endI][endJ])){
                return;
            }
          Cell t;
          if(current.i-1>=0){
             t = grid[current.i-1][current.j];
             checkAndUpdateCost(current, t, current.finalCost+V_H_COST);
             if(current.j-1>=0){
                t = grid[current.i-1][current.j-1];
                checkAndUpdateCost(current, t, current.finalCost+DIAGONAL_COST);
             }
              if(current.j+1<grid[0].length){
                 t = grid[current.i-1][current.j+1];
                 checkAndUpdateCost(current, t, current.finalCost+DIAGONAL_COST);
              }
          }
          if(current.j-1>=0){
             t = grid[current.i][current.j-1];
             checkAndUpdateCost(current, t, current.finalCost+V_H_COST);
}
                                                                                      22 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                          190640107029
if(current.j+1<grid[0].length){
           t = grid[current.i][current.j+1];
           checkAndUpdateCost(current, t, current.finalCost+V_H_COST);
        }
       if(current.i+1<grid.length){
          t = grid[current.i+1][current.j];
          checkAndUpdateCost(current, t, current.finalCost+V_H_COST);
       if(current.j-1>=0){
             t = grid[current.i+1][current.j-1];
             checkAndUpdateCost(current, t, current.finalCost+DIAGONAL_COST);
          }
if(current.j+1<grid[0].length){
             t = grid[current.i+1][current.j+1];
              checkAndUpdateCost(current, t, current.finalCost+DIAGONAL_COST);
           }
        }
      }
}
/*
  Params :
  tCase = test case No.
  x, y = Board's dimensions
  si, sj = start location's x and y
  coordinatesei, ej = end location's x and y
  coordinates
  int[][] blocked = array containing inaccessible cell coordinates
*/
  public static void test(int tCase, int x, int y, int si, int sj, int ei, int ej, int[]
       [] blocked){System.out.println("\n\nTest Case #"+tCase);
        //Reset
       grid = new Cell[x][y];
  closed = new boolean[x]
  [y];
       open = new PriorityQueue<>((Object o1, Object o2) ->
     {Cell c1 = (Cell)o1;
           Cell c2 =
           (Cell)o2;
           return c1.finalCost<c2.finalCost?-1:
                                                                                             23 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)   190640107029
c1.finalCost>c2.finalCost?1:0;
        });
                                      24 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                         190640107029
       for(int i=0;i<x;++i)
      {for(int j=0;j<y;++j){
             grid[i][j] = new Cell(i, j);
             grid[i][j].heuristicCost = Math.abs(i-endI)+Math.abs(j-endJ);
//            System.out.print(grid[i][j].heuristicCost+" ");
          }
//          System.out.println();
       }
       grid[si][sj].finalCost = 0;
       /*
         Set blocked cells. Simply set the cell values to null
         for blocked cells.
       */
      for(int
         i=0;i<blocked.length;++i){ setBlocked(bl
         ocked[i][0], blocked[i][1]);
      }
 System.out.println("Grid: ");
        for(int i=0;i<x;++i)
      {for(int j=0;j<y;++j){
             if(i==si&&j==sj)System.out.print("SO "); //Source
             else if(i==ei && j==ej)System.out.print("DE "); //Destination
AStar();
                                                                                            25 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                    190640107029
       for(int j=0;j<x;++j){
             if(grid[i][j]!=null)System.out.printf("%-3d ", grid[i][j].finalCost);
 else System.out.print("BL ");
          }
          System.out.println();
        }
        System.out.println();
         if(closed[endI][endJ]){
        //Trace back the path
             System.out.println("Path: ");
             Cell current = grid[endI][endJ];
             System.out.print(current);
    while(current.parent!=null){
                System.out.print(" -> "+current.parent);
      current = current.parent;
             }
             System.out.println();
         }else System.out.println("No possible path");
    }
                                                                                       26 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                               190640107029
PRACTICAL - 6
Program :-
solution(Queens) :-
permutation([1,2,3,4,5,6,7,8], Queens),
safe(Queens).
permutation([],[]).
permutation([Head|Tail],PermList) :-
permutation(Tail,PermTail),
del(Head,PermList,PermTail).
del(Item,[Item|List],List). del(Item,
[First|List],[First|List1]) :-
del(Item,List,List1).
safe([]). safe([Queen|
Others]) :- safe(Others),
noattack(Queen,Others,1).
noattack(_,[],_). noattack(Y,
[Y1|Ylist],Xdist) :- Y1-Y=\
=Xdist,
 Y-Y1=\=Xdist, Dist1
 is Xdist + 1,
 noattack(Y,Ylist,Dist1).
                                                                  27 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                               190640107029
PRACTICAL - 7
Program :-
sum(N1,N2,N):- sum1(N1,N2,N,0,0,
[0,1,2,3,4,5,6,7,8,9],_).
sum1([],[],[],C,C,Digits,Digits).
sum1([D1|N1],[D2|N2],[D|N],C1,C,Digs1,Digs):-
 sum1(N1,N2,N,C1,C2,Digs1,Digs2),
 digitsum(D1,D2,C2,D,C,Digs2,Digs).
digitsum(D1,D2,C1,D,C,Digs1,Digs):-
del(D1,Digs1,Digs2),
del(D2,Digs2,Digs3), del(D,Digs3,Digs),
S is D1+D2+C1,
 D is S mod
10, C is S //
10. del(A,L,L):-
 nonvar(A),!.
del(A,[A|L],L).
del(A,[B|L],[B|L1]):-
del(A,L,L1).
% Some puzzles puzzle1([D,O,N,A,L,D],[G,E,R,A,L,D],
[R,O,B,E,R,T]).
puzzle2([0,S,E,N,D], [0,M,O,R,E],[M,O,N,E,Y]).
                                                                  28 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                    190640107029
PRACTICAL - 8
Program :-
domains
 town = symbol
 distance = unsigned
 rib = r(town,town,distance)
 tlist = town*
 rlist = rib*
predicates
 nondeterm way(town,town,rlist,distance)
 nondeterm route(town,town,rlist,tlist,distance)
 nondeterm route1(town,tlist,rlist,tlist,distance)
 nondeterm ribsmember(rib,rlist)
 nondeterm townsmember(town,tlist)
 nondeterm tsp(town,town,tlist,rlist,tlist,distance)
 nondeterm ham(town,town,tlist,rlist,tlist,distance)
 nondeterm shorterRouteExists(town,town,tlist,rlist,distance)
 nondeterm alltown(tlist,tlist)
 nondeterm write_list(tlist)
clauses
 write_list([]).
 write_list([H|T]):-
 write(H,‘ ‘), write_list(T).
 townsmember(X,[X|_]).
 townsmember(X,[_|L]):-
 townsmember(X,L).
 ribsmember(r(X,Y,D),[r(X,Y,D)|_]).
 ribsmember(X,[_|L]):-
 ribsmember(X,L).
 alltown(_,[]).
 alltown(Route,[H|T]):-
  townsmember(H,Route),
                                                                       29 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                              190640107029
  alltown(Route,T).
 way(Town1,Town2,Ways,OutWayDistance):-
 ribsmember(r(Town1,Town2,D),Ways), OutWayDistance
 =
 D. route(Town1,Town2,Ways,OutRoute,OutDistance):-
 route1(Town1,[Town2],Ways,OutRoute,T1T2Distance),
%SWITCH HERE
  way(Town2,Town1,Ways,LasDist),
OutDistance = T1T2Distance + LasDist. route1(Town1,[Town1|
Route1],_,[Town1|Route1],OutDistance):-
  OutDistance = 0. route1(Town1,[Town2|
 PassedRoute],Ways,OutRoute,OutDistance):-
 way(TownX,Town2,Ways,WayDistance),
 not(townsmember(TownX,PassedRoute)),
route1(Town1,[TownX,Town2|PassedRoute],Ways,OutRoute,CompletingRoadDistance)
 OutDistance = CompletingRoadDistance + WayDistance.
 shorterRouteExists(Town1,Town2,Towns,Ways,Distance):-
   ham(Town1,Town2,Towns,Ways,_,Other),
     Other < Distance.
 tsp(Town1,Town1,Towns,Ways,BestRoute,MinDistance):- way(OtherTown,Town1,Ways,_),
    tsp(Town1,OtherTown,Towns,Ways,BestRoute,MinDistance).
 tsp(Town1,Town2,Towns,Ways,BestRoute,MinDistance):-
    ham(Town1,Town2,Towns,Ways,Route,Distance),
    not(shorterRouteExists(Town1,Town2,Towns,Ways,Distance)),
  BestRoute = Route,
  MinDistance = Distance.
 ham(Town1,Town2,Towns,Ways,Route,Distance):-route(Town1,Town2,Ways,Route,Distance),
%SWITCH HERE
  alltown(Route,Towns), % if you want simple road without including all towns youcould
uncomment this line
  write_list(Route),
  write(” tD = “,Distance,“n“).
% fail.
                                                                                  30 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                    190640107029
PRACTICAL - 9
Solution:
Semantic Nets:
These are an alternative to predicate logic as a form of knowledge representation.
The idea is that we can store our knowledge in form of a graph with nodes representing
object in the world and arcs representing relationships between those objects.
For example:
                                                                                       31 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)   190640107029
                                      32 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                   190640107029
                                      34 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                         190640107029
Is_colored(tom,ginger).
In general, an is_a link between a class c and an individual m is represented by fact c(m).
An a_kind_of link between a subclass c and a superclass s is represented by s(x):-c(x).
INHERITANCE:
The prolog equivalent captures an important property of semantic nets that they may be
usedfor a form of inference known as inheritance.
The idea of this is that if an object belongs to class, it inherits all the properties of that class.
For example: As we have a “likes” link between cats and cream, meaning in “all the cats like
cream”, we can infer that any object which has an is_a link to cats will like cream. So both
TOM and CAT1 will like cream.
Inheritance also applies across the a_kind_of links. For example, any property of mammals
oranimals will automatic be a property of cats. So, we can infer, for example, that TOM has
fur,since TOM is a cat, a cat is a kind of animal, all animals are mammals and all mammals
havefur.
                                                                                             35 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                    190640107029
 FRAMES:
 Frames are a variant of semantic networks. A frame is a data structure for representing
 a stereo typical situation.
 All the information relevant to a concept is stored in a single complex entity called a frame.
 Superficially, frames look like record, data structures or class, frames also support
 inheritance. In frame based systems we refer to:
 ·   Objects     - mammal
 ·   Slots        - properties such as color and size
 ·   Slot values- values stored in slots such as grey and large.
 Slots and the corresponding slot values are inherited through the class
 hierarchy. FEATURES:
 These are more natural support of values then semantic nets.
 Frames can be easily implemented using object oriented programming technique.
 In Frames based system, Inheritance is easily controlled.
 BENEFITS:
 ·   Easily understood by non-developers.
 ·   Expressive power.
 ·   Easy to include default information and detect missing
 values. DRAWBACKS:
 ·   No standards.
 ·   No inference mechanism.
                                                                                         36 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                     190640107029
PRACTICAL - 10
Solution :-
It has been used by many programs that portend to understand English (MARGIE, SAM,
PAM). CD developed by Schank et al. as were the previous examples.
CD provides:
Sentences are represented as a series of diagrams depicting actions using both abstract and
real physical situations.
ATRANS
        -- Transfer of an abstract relationship. e.g. give.
PTRANS
        -- Transfer of the physical location of an object. e.g. go.
PROPEL
                                                                                        37 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                  190640107029
       -- 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. ????.
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.
                                                                                      38 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                               190640107029
        o
        -- object.
        R
        -- recipient-donor.
        I
        -- instrument e.g. eat with a spoon.
        D
       Double arrows ( ) indicate two-way links between the actor (PP) and action (ACT).
       The actions are built from the set of primitive acts (see above).
             o These can be modified by tense etc.
       The use of tense and mood in describing events is extremely important and
        schank introduced the following modifiers:
       p
       -- past
       f
       -- future
       t
       -- transition
    
       -- start transition
    
       -- finished transition
       k
       -- continuing
       ?
       -- interrogative
       /
       -- negative
       delta
       -- timeless
                                                                                   39 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                   190640107029
      c
      -- conditional
      the absence of any modifier implies the present tense.
      So the past tense of the above example:
      John gave Mary a book becomes:
The has an object (actor), PP and action, ACT. I.e. PP ACT. The triplearrow (               )
is also a two link but between an object, PP, and its attribute, PA. I.e. PP PA.
Primitive states are used to describe many state descriptions such as height, health, mental
state, physical state.
There are many more physical states than primitive actions. They use a numeric scale.
E.g. John           height(+10) John is the tallest John height(< average) John is short
Frank Zappahealth(-10) Frank Zappa is dead Davemental_state(-10) Dave is
sad Vase     physical_state(-10) The vase is broken
You can also specify things like the time of occurrence in the relation ship.
Now let us consider a more complex sentence: Since smoking can kill you, I stopped Lets
look at how we represent the inference that smoking can kill:
                                                                                        40 | P a g e
ARTIFICIAL INTELLIGENCE (3170716)                                                       190640107029
Advantages of CD:
Disadvantages of CD:
Dave bet Frank five pounds that Wales would win the Rugby World Cup.
41 | P a g e