Professional Documents
Culture Documents
Practical-file
SESSION-2021-2022
1
ARTIFICIAL INTELLIGENCE BTCS511
INDEX
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;
Graph::Graph(int V)
3
ARTIFICIAL INTELLIGENCE BTCS511
{
this->V = V;
adj.resize(V);
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
vector<bool> visited;
visited.resize(V,false);
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
4
ARTIFICIAL INTELLIGENCE BTCS511
queue.pop_front();
5
ARTIFICIAL INTELLIGENCE BTCS511
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;
void Graph::DFS(int v)
{
// Mark the current node as visited and
7
ARTIFICIAL INTELLIGENCE BTCS511
// print it
visited[v] = true;
cout << v << " ";
// 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);
// 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;
10
ARTIFICIAL INTELLIGENCE BTCS511
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;
13
ARTIFICIAL INTELLIGENCE BTCS511
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
#include<bits/stdc++.h>
// Initial values of
bool maximizingPlayer,
int beta)
16
ARTIFICIAL INTELLIGENCE BTCS511
if (depth == 3)
return values[nodeIndex];
if (maximizingPlayer)
// right children
break;
return best;
17
ARTIFICIAL INTELLIGENCE BTCS511
else
// right children
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
// stores matrix
int mat[N][N];
20
ARTIFICIAL INTELLIGENCE BTCS511
21
ARTIFICIAL INTELLIGENCE BTCS511
node->x = newX;
node->y = newY;
return node;
}
22
ARTIFICIAL INTELLIGENCE BTCS511
{
if (root == NULL)
return;
printPath(root->parent);
printMatrix(root->mat);
printf("\n");
}
23
ARTIFICIAL INTELLIGENCE BTCS511
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);
// 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}
};
25
ARTIFICIAL INTELLIGENCE BTCS511
int final[N][N] =
{
{1, 2, 3},
{5, 8, 6},
{0, 7, 4}
};
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;
28
ARTIFICIAL INTELLIGENCE BTCS511
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)]
#}
30
ARTIFICIAL INTELLIGENCE BTCS511
27
BTCS511 Artificial Intelligence
'D': 1
}
return H[n]
g[start_node] = 0
if n == None:
print('Path does not exist!')
return None
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()
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
32
ARTIFICIAL INTELLIGENCE BTCS511
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)
model=
BayesianModel([('age','heartdisease'),('sex','heartdisease'),('exang','heartdisease'),('cp','heartdise
as e'),('heartdisease','restecg'),('heartdisease','chol')])
33
ARTIFICIAL INTELLIGENCE BTCS511
34
ARTIFICIAL INTELLIGENCE BTCS511
EXPERIMENT – 10
Write a program to implement Mini Project: tic tac toe
import random
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)
self.board[row][col] = 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]
break
if win:
return win
return False
if item == '-':
return False
return True
def is_board_filled(self):
37
ARTIFICIAL INTELLIGENCE BTCS511
if item == '-':
return False
return True
def show_board(self):
print()
def start(self):
self.create_board()
self.show_board()
38
ARTIFICIAL INTELLIGENCE BTCS511
").split())) print(
won or not if
self.is_player_win(player):
draw or not if
self.is_board_filled():
print("Match Draw!")
break
player =
self.swap_player_turn(player
board
print()
self.show_board()
tic_tac_toe = TicTacToe()
39
ARTIFICIAL INTELLIGENCE BTCS511
tic_tac_toe.start()
Output-
40