You are on page 1of 40

ARTIFICIAL INTELLIGENCE BTCS511

Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore


Shri Vaishnav Institute of Information Technology
Department of Computer Science & Engineering

Practical-file
SESSION-2021-2022

B.TECH | III Year | 5th Semester


Enrolment No.:20100BTCSE07515

SUBJECT NAME: Artificial Intelligence


SUBJECT CODE : BTCS511

SUBMITTED By:- SUBMITTED To:-


Annanya Badarya Prof. Gourav Makwana

1
ARTIFICIAL INTELLIGENCE BTCS511

Shri Vaishnav Institute of Information Technology


Shri Vaishnav Institute of Information Technology
Department of Computer Science & Engineering

B.TECH | III Year | 5th Semester


Enrolment No.:20100BTCSE07515
SUBJECT NAME: Artificial Intelligence
SUBJECT CODE : BTCS511

INDEX

S.No. Experiment Name Date Remarks


1. Write a program to implement breadth First Search
2. Write a program to implement depth First Search
3. Write a program to implement dest First Search
4. Write a program to implement Min-Max
Algorithm for Game Search
5. Write a program to implement Alpha-Beta Pruning
for Game Search
6. Write a program to implement 8-puzzle Informed
Search
7. Write a program to implement 8-puzzle
Uninformed Search
8. Write a program to implement A* Algorithm
9. Write a programme to construct a Besiyan-Network
from given data
10. Write a program to implement mini Project: Tic
Tac Toe

2
ARTIFICIAL INTELLIGENCE BTCS511

Experiment - 1
Write a programme to conduct Breadth First Search.
// Program to print BFS traversal from a given
// source vertex. BFS(int s) traverses vertices
// reachable from s.
#include<bits/stdc++.h>
using namespace std;

// This class represents a directed graph using


// adjacency list representation
class Graph
{
int V; // No. of vertices

// Pointer to an array containing adjacency


// lists
vector<list<int>> adj;
public:
Graph(int V); // Constructor

// function to add an edge to graph


void addEdge(int v, int w);

// prints BFS traversal from a given source s


void BFS(int s);
};

Graph::Graph(int V)

3
ARTIFICIAL INTELLIGENCE BTCS511

{
this->V = V;
adj.resize(V);
}

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{
// Mark all the vertices as not visited
vector<bool> visited;
visited.resize(V,false);

// Create a queue for BFS


list<int> queue;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue.push_back(s);

while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";

4
ARTIFICIAL INTELLIGENCE BTCS511

queue.pop_front();

// Get all adjacent vertices of the dequeued


// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (auto adjecent: adj[s])
{
if (!visited[adjecent])
{
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}

// Driver program to test methods of graph class


int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

5
ARTIFICIAL INTELLIGENCE BTCS511

cout << "Following is Breadth First Traversal "


<< "(starting from vertex 2) \n";
g.BFS(2);

return 0;
}
Output-

6
ARTIFICIAL INTELLIGENCE BTCS511

Experiment - 2
Write a programme to conduct Depth First Search.
// C++ program to print DFS traversal from
// a given vertex in a given graph
#include <bits/stdc++.h>
using namespace std;

// Graph class represents a directed graph


// using adjacency list representation
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;

// function to add an edge to graph


void addEdge(int v, int w);

// DFS traversal of the vertices


// reachable from v
void DFS(int v);
};

void Graph::addEdge(int v, int w)


{
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::DFS(int v)
{
// Mark the current node as visited and

7
ARTIFICIAL INTELLIGENCE BTCS511

// print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent


// to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}

// Driver's code
int main()
{
// Create a graph given in the above diagram
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);

cout << "Following is Depth First Traversal"


" (starting from vertex 2) \n";

// Function call
g.DFS(2);

8
ARTIFICIAL INTELLIGENCE BTCS511

return 0;
}
Output –

9
ARTIFICIAL INTELLIGENCE BTCS511

Experiment – 3
Write a programme to conduct Best First Search.
// C++ program to implement Best First Search using priority
// queue
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;

vector<vector<pi> > graph;

// Function for adding edges to 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));
}

// Function For Implementing Best First Search


// Gives output path having lowest cost
void best_first_search(int actual_Src, int target, int n)
{
vector<bool> visited(n, false);
// MIN HEAP priority queue
priority_queue<pi, vector<pi>, greater<pi> > pq;
// sorting in pq gets done by first value of pair
pq.push(make_pair(0, actual_Src));
int s = actual_Src;
visited[s] = true;
while (!pq.empty()) {
int x = pq.top().second;

10
ARTIFICIAL INTELLIGENCE BTCS511

// Displaying the path having lowest cost


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

// Driver code to test above methods


int main()
{
// No. of Nodes
int v = 14;
graph.resize(v);

// The nodes shown in above example(by alphabets) are


// implemented using integers addedge(x,y,cost);
addedge(0, 1, 3);
addedge(0, 2, 6);
addedge(0, 3, 5);
addedge(1, 4, 9);
addedge(1, 5, 8);
addedge(2, 6, 12);

11
ARTIFICIAL INTELLIGENCE BTCS511

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

int source = 0;
int target = 9;

// Function call
best_first_search(source, target, v);

return 0;
}
Output

12
ARTIFICIAL INTELLIGENCE BTCS511

Experiment - 4
Write a programme to conduct Min-Max Algorithm for Game Search.
// A simple C++ program to find
// maximum score that
// maximizing player can get.
#include<bits/stdc++.h>
using namespace std;

// Returns the optimal value a maximizer can obtain.


// depth is current depth in game tree.
// nodeIndex is index of current node in scores[].
// isMax is true if current move is

13
ARTIFICIAL INTELLIGENCE BTCS511

// of maximizer, else false


// scores[] stores leaves of Game tree.
// h is maximum height of Game tree
int minimax(int depth, int nodeIndex, bool isMax,
int scores[], int h)
{
// Terminating condition. i.e
// leaf node is reached
if (depth == h)
return scores[nodeIndex];

// If current move is maximizer,


// find the maximum attainable
// value
if (isMax)
return max(minimax(depth+1, nodeIndex*2, false, scores, h),
minimax(depth+1, nodeIndex*2 + 1, false, scores, h));

// Else (If current move is Minimizer), find the minimum


// attainable value
else
return min(minimax(depth+1, nodeIndex*2, true, scores, h),
minimax(depth+1, nodeIndex*2 + 1, true, scores, h));
}

// A utility function to find Log n in base 2


int log2(int n)
{
return (n==1)? 0 : 1 + log2(n/2);
}

14
ARTIFICIAL INTELLIGENCE BTCS511

// Driver code
int main()
{
// The number of elements in scores must be
// a power of 2.
int scores[] = {3, 5, 2, 9, 12, 5, 23, 23};
int n = sizeof(scores)/sizeof(scores[0]);
int h = log2(n);
int res = minimax(0, 0, true, scores, h);
cout << "The optimal value is : " << res << endl;
return 0;
}
Output -

15
ARTIFICIAL INTELLIGENCE BTCS511

Experiment – 5

Write a programme to conduct Alpha-Beta Pruning for Game Search.


// C++ program to demonstrate

// working of Alpha-Beta Pruning

#include<bits/stdc++.h>

using namespace std;

// Initial values of

// Alpha and Beta

const int MAX = 1000;

const int MIN = -1000;

// Returns optimal value for

// current player(Initially called

// for root and maximizer)

int minimax(int depth, int nodeIndex,

bool maximizingPlayer,

int values[], int alpha,

int beta)

// Terminating condition. i.e

// leaf node is reached

16
ARTIFICIAL INTELLIGENCE BTCS511

if (depth == 3)

return values[nodeIndex];

if (maximizingPlayer)

int best = MIN;

// Recur for left and

// right children

for (int i = 0; i < 2; i++)

int val = minimax(depth + 1, nodeIndex * 2 + i,

false, values, alpha, beta);

best = max(best, val);

alpha = max(alpha, best);

// Alpha Beta Pruning

if (beta <= alpha)

break;

return best;

17
ARTIFICIAL INTELLIGENCE BTCS511

else

int best = MAX;

// Recur for left and

// right children

for (int i = 0; i < 2; i++)

int val = minimax(depth + 1, nodeIndex * 2 + i,

true, values, alpha, beta);

best = min(best, val);

beta = min(beta, best);

// Alpha Beta Pruning

if (beta <= alpha)

break;

return best;

// Driver Code

int main()

18
ARTIFICIAL INTELLIGENCE BTCS511

int values[8] = { 3, 5, 6, 9, 1, 2, 0, -1 };

cout <<"The optimal value is : "<< minimax(0, 0, true, values, MIN, MAX);;

return 0;

Output -

19
ARTIFICIAL INTELLIGENCE BTCS511

Experiment – 6
Write a project to conduct 8-puzzle Informed Search.
#include <bits/stdc++.h>
using namespace std;
#define N 3

// state space tree nodes


struct Node
{
// stores the parent node of the current node
// helps in tracing path when the answer is found
Node* parent;

// stores matrix
int mat[N][N];

// stores blank tile coordinates


int x, y;

// stores the number of misplaced tiles


int cost;

// stores the number of moves so far


int level;
};

// Function to print N x N matrix


int printMatrix(int mat[N][N])
{

20
ARTIFICIAL INTELLIGENCE BTCS511

for (int i = 0; i < N; i++)


{
for (int j = 0; j < N; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
}

// Function to allocate a new node


Node* newNode(int mat[N][N], int x, int y, int newX,
int newY, int level, Node* parent)
{
Node* node = new Node;

// set pointer for path to root


node->parent = parent;

// copy data from parent node to current node


memcpy(node->mat, mat, sizeof node->mat);

// move tile by 1 position


swap(node->mat[x][y], node->mat[newX][newY]);

// set number of misplaced tiles


node->cost = INT_MAX;

// set number of moves so far


node->level = level;

// update new blank tile coordinates

21
ARTIFICIAL INTELLIGENCE BTCS511

node->x = newX;
node->y = newY;

return node;
}

// bottom, left, top, right


int row[] = { 1, 0, -1, 0 };
int col[] = { 0, -1, 0, 1 };

// Function to calculate the number of misplaced tiles


// ie. number of non-blank tiles not in their goal position
int calculateCost(int initial[N][N], int final[N][N])
{
int count = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
if (initial[i][j] && initial[i][j] != final[i][j])
count++;
return count;
}

// Function to check if (x, y) is a valid matrix coordinate


int isSafe(int x, int y)
{
return (x >= 0 && x < N && y >= 0 && y < N);
}

// print path from root node to destination node


void printPath(Node* root)

22
ARTIFICIAL INTELLIGENCE BTCS511

{
if (root == NULL)
return;
printPath(root->parent);
printMatrix(root->mat);

printf("\n");
}

// Comparison object to be used to order the heap


struct comp
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return (lhs->cost + lhs->level) > (rhs->cost + rhs->level);
}
};

// Function to solve N*N - 1 puzzle algorithm using


// Branch and Bound. x and y are blank tile coordinates
// in initial state
void solve(int initial[N][N], int x, int y,
int final[N][N])
{
// Create a priority queue to store live nodes of
// search tree;
priority_queue<Node*, std::vector<Node*>, comp> pq;

// create a root node and calculate its cost


Node* root = newNode(initial, x, y, x, y, 0, NULL);

23
ARTIFICIAL INTELLIGENCE BTCS511

root->cost = calculateCost(initial, final);

// Add root to list of live nodes;


pq.push(root);

// Finds a live node with least cost,


// add its childrens to list of live nodes and
// finally deletes it from the list.
while (!pq.empty())
{
// Find a live node with least estimated cost
Node* min = pq.top();

// The found node is deleted from the list of


// live nodes
pq.pop();

// if min is an answer node


if (min->cost == 0)
{
// print the path from root to destination;
printPath(min);
return;
}

// do for each child of min


// max 4 children for a node
for (int i = 0; i < 4; i++)
{
if (isSafe(min->x + row[i], min->y + col[i]))

24
ARTIFICIAL INTELLIGENCE BTCS511

{
// create a child node and calculate
// its cost
Node* child = newNode(min->mat, min->x,
min->y, min->x + row[i],
min->y + col[i],
min->level + 1, min);
child->cost = calculateCost(child->mat, final);

// Add child to list of live nodes


pq.push(child);
}
}
}
}

// Driver code
int main()
{
// Initial configuration
// Value 0 is used for empty space
int initial[N][N] =
{
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};

// Solvable Final configuration


// Value 0 is used for empty space

25
ARTIFICIAL INTELLIGENCE BTCS511

int final[N][N] =
{
{1, 2, 3},
{5, 8, 6},
{0, 7, 4}
};

// Blank tile coordinates in initial


// configuration
int x = 1, y = 2;

solve(initial, x, y, final);

return 0;
}
Output –

26
ARTIFICIAL INTELLIGENCE BTCS511

Experiment – 7
Write a programme to conduct 8-puzzle Uninformed Search.
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.
Solution
Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. We
can perform a Breadth-first search on the state space tree. This always finds a goal state nearest
tothe root. But no matter what the initial state is, the algorithm attempts the same sequence of
moves
like DFS
c(x) = f(x) + h(x) where
f(x) is the length of the path from root to x
(the number of moves so far) and
h(x) is the number of non-blank tiles not in
their goal position (the number of mis-
-placed tiles). There are at least h(x)
moves to transform state x to a goal state

27
ARTIFICIAL INTELLIGENCE BTCS511

struct list_node
{
list_node *next;

// Helps in tracing path when answer is found


list_node *parent;
float cost;
}
algorithm LCSearch(list_node *t)
{

28
ARTIFICIAL INTELLIGENCE BTCS511

// Search t for an answer node


// Input: Root node of tree t
// Output: Path from answer node to root
if (*t is an answer node)
{
print(*t);
return;
}
E = t; // E-node
Initialize the list of live nodes to be empty;
while (true)
{
for each child x of E
{
if x is an answer node
{
print the path from x to t;
return;
}
Add (x); // Add x to list of live nodes;
x->parent = E; // Pointer for path to root
}

if there are no more live nodes


{
print ("No answer node");
return;
}

// Find a live node with least estimated cost


E = Least();
}

Result the path followed by the above algorithm to reach the final configuration from the
given initial configuration of the 8-Puzzle

29
ARTIFICIAL INTELLIGENCE BTCS511

EXPERIMENT – 8
Write a program to implement A* Algorithm
A* is based on using heuristic methods to achieve optimality and completeness, and is a variant of the
best-first algorithm.

When a search algorithm has the property of optimality, it means it is guaranteed to find
the best possible solution, in our case the shortest path to the finish state. When a search
algorithm has the property of completeness, it means that if a solution to a given
problem exists, the algorithm is guaranteed to find it.
Each time A* enters a state, it calculates the cost, f(n) (n being the neighboring node), to
travel to all of the neighboring nodes, and then enters the node with the lowest value of
f(n).
These values are calculated with the following formula:
$$
\mathcal f(n) = \mathcal g(n) + \mathcal h(n)

Program Code:
from collections import deque

class Graph:
# example of adjacency list (or rather map)
# adjacency_list = {
# 'A': [('B', 1), ('C', 3), ('D', 7)],
# 'B': [('D', 5)],
# 'C': [('D', 12)]
#}

def __init__(self, adjacency_list):


self.adjacency_list = adjacency_list

def get_neighbors(self, v):


return self.adjacency_list[v]

# heuristic function with equal values for all nodes


def h(self, n):
H={
'A': 1,
'B': 1,
'C': 1,

30
ARTIFICIAL INTELLIGENCE BTCS511

27
BTCS511 Artificial Intelligence

'D': 1
}

return H[n]

def a_star_algorithm(self, start_node, stop_node):


# open_list is a list of nodes which have been visited, but who's
neighbors # haven't all been inspected, starts off with the start
node # closed_list is a list of nodes which have been visited
# and who's neighbors have been inspected
open_list = set([start_node])
closed_list = set([])

# g contains current distances from start_node to all


other nodes # the default value (if it's not found in the
map) is +infinity g = {}

g[start_node] = 0

# parents contains an adjacency map of all nodes


parents = {}
parents[start_node] = start_node

while len(open_list) > 0:


n = None

# find a node with the lowest value of f() - evaluation


function for v in open_list:
if n == None or g[v] + self.h(v) < g[n] + self.h(n):
n = v;

if n == None:
print('Path does not exist!')
return None

# if the current node is the stop_node


# then we begin reconstructin the path from it to the
start_node if n == stop_node:
reconst_path = []

31
ARTIFICIAL INTELLIGENCE BTCS511

28
BTCS511 Artificial Intelligence

while parents[n] != n:
reconst_path.append(n)
n = parents[n]

reconst_path.append(start_node)

reconst_path.reverse()

print('Path found: {}'.format(reconst_path))


return reconst_path

# for all neighbors of the current node do


for (m, weight) in self.get_neighbors(n):
# if the current node isn't in both open_list and
closed_list # add it to open_list and note n as it's
parent
if m not in open_list and m not in
closed_list: open_list.add(m)
parents[m] = n
g[m] = g[n] + weight

# otherwise, check if it's quicker to first visit


n, then m # and if it is, update parent data and
g data
# and if the node was in the closed_list, move it to
open_list else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n

if m in closed_list:
closed_list.remove(m)
open_list.add(m)

# remove n from the open_list, and add it to


closed_list # because all of his neighbors were
inspected open_list.remove(n)
closed_list.add(n)

32
ARTIFICIAL INTELLIGENCE BTCS511

print('Path does not exist!')


return None

EXPERIMENT – 9
Write a programme to construct a Besiyan-Network from given
Data.
A Bayesian Network falls under the category of Probabilistic Graphical Modelling (PGM) technique that
is used to compute uncertainties by using the concept of probability. Popularly known as Belief
Networks, Bayesian Networks are used to model uncertainties by using Directed Acyclic Graphs (DAG).

Program code:
import numpy as np
import pandas as pd
import csv
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination

heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)

print('Sample instances from the dataset are given below')


print(heartDisease.head())

print('\n Attributes and datatypes')


print(heartDisease.dtypes)

model=
BayesianModel([('age','heartdisease'),('sex','heartdisease'),('exang','heartdisease'),('cp','heartdise
as e'),('heartdisease','restecg'),('heartdisease','chol')])

33
ARTIFICIAL INTELLIGENCE BTCS511

print('\nLearning CPD using Maximum likelihood estimators')


model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

print('\n Inferencing with Bayesian Network:')


HeartDiseasetest_infer = VariableElimination(model)

print('\n 1. Probability of HeartDisease given evidence= restecg')


q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'restecg':1}) print(q1)

print('\n 2. Probability of HeartDisease given evidence= cp ')


q2=HeartDiseasetest_infer.query(variables=['heartdisease'],evidenc={'cp':2}) print(q2)

34
ARTIFICIAL INTELLIGENCE BTCS511

EXPERIMENT – 10
Write a program to implement Mini Project: tic tac toe
import random

print("ANNANYA BADARYA 20100BTCSE07515")

class TicTacToe:

def __init__(self):

self.board = []

def create_board(self):

for i in range(3):

row = []

for j in range(3):

row.append('-')

self.board.append(row)

def get_random_first_player(self):

return random.randint(0, 1)

def fix_spot(self, row, col, player):

self.board[row][col] = player

def is_player_win(self, player):

win = None

35
ARTIFICIAL INTELLIGENCE BTCS511

n = len(self.board)

# checking rows

for i in range(n):

win = True

for j in range(n):

if self.board[i][j]

!= player: win =

False

break

if win:

return win

# checking columns

for i in range(n):

win = True

for j in range(n):

if self.board[j][i]

!= player: win =

False

break

if win:

return win

# checking diagonals

36
ARTIFICIAL INTELLIGENCE BTCS511

win = True

for i in range(n):

if self.board[i][i]

!= player: win =

False

break

if win:

return win

win = True

for i in range(n):

if self.board[i][n - 1 - i]

!= player: win = False

break

if win:

return win

return False

for row in self.board:

for item in row:

if item == '-':

return False

return True

def is_board_filled(self):

37
ARTIFICIAL INTELLIGENCE BTCS511

for row in self.board:

for item in row:

if item == '-':

return False

return True

def swap_player_turn(self, player):

return 'X' if player == 'O' else 'O'

def show_board(self):

for row in self.board:

for item in row:

print(item, end=" ")

print()

def start(self):

self.create_board()

player = 'X' if self.get_random_first_player() ==

1 else 'O' while True:

print(f"Player {player} turn")

self.show_board()

# taking user input

row, col = list(

38
ARTIFICIAL INTELLIGENCE BTCS511

map(int, input("Enter row and column numbers to fix spot:

").split())) print(

# fixing the spot

self.fix_spot(row - 1, col - 1, player) #

checking whether current player is

won or not if

self.is_player_win(player):

print(f"Player {player} wins

the game!") break

# checking whether the game is

draw or not if

self.is_board_filled():

print("Match Draw!")

break

# swapping the turn

player =

self.swap_player_turn(player

) # showing the final view of

board

print()

self.show_board()

# starting the game

tic_tac_toe = TicTacToe()

39
ARTIFICIAL INTELLIGENCE BTCS511

tic_tac_toe.start()

Output-

40

You might also like