AI Programming List
AI Programming List
9.
10. Write a program to solve N-Queens problem.
11. Write a program to Implement A* Algorithm.
12. Write a program to implement Single Player Game (Using any Heuristic
Function)
13. Write a program to solve 8 puzzle problem.
14. Write a program to solve travelling salesman problem
Prolog programming:
15.Assume given a set of facts of the form father(name1,name2) (name1 is the
father of name2).
Say which answers, and in which order, are generated by your definitions for
the following queries in Prolog: ?- brother(X,Y). ?- cousin(X,Y). ?-
grandson(X,Y). ?- descendent(X,Y).
PRACTICAL NO.1
AIM: -Introduction of Artificial Intelligence and its application.
1.2 Goals of AI
To Create Expert Systems − The systems which exhibit intelligent behavior, learn,
demonstrate, explain, and advice its users.
To Implement Human Intelligence in Machines − Creating systems that understand, think,
learn, and behave like humans.
1.3 Advantages of Artificial Intelligence
o More powerful are more useful computers
o New and improved interfaces
o Solving new problems
o Better handling of information
o Relieves information overload
o Conversion of information into knowledge
1.4 Disadvantages of Artificial Intelligence
o Increased costs
o Difficulty with software development-slow and expensive
o Few experienced programmers
o Few practical products have reached the market as yet
1.5 Foundation of AI: -
Fig.1.1
1.6 Applications of AI: -
AI has been dominant in various fields such as −
Gaming − AI plays crucial role in strategic games such as chess, poker, tic-tac-toe, etc.,
where machine can think of large number of possible positions based on heuristic
knowledge.
Natural Language Processing − It is possible to interact with the computer that
understands natural language spoken by humans.
Expert Systems − There are some applications which integrate machine, software, and
special information to impart reasoning and advising. They provide explanation and advice
to the users.
Vision Systems − These systems understand, interpret, and comprehend visual input on
the computer. For example,
o A spying aeroplane takes photographs, which are used to figure out spatial information
or map of the areas.
o Doctors use clinical expert system to diagnose the patient.
o Police use computer software that can recognize the face of criminal with the stored
portrait made by forensic artist.
Speech Recognition − Some intelligent systems are capable of hearing and comprehending
the language in terms of sentences and their meanings while a human talks to it. It can
handle different accents, slang words, noise in the background, change in human’s noise
due to cold, etc.
Handwriting Recognition − The handwriting recognition software reads the text written on
paper by a pen or on screen by a stylus. It can recognize the shapes of the letters and
convert it into editable text.
Intelligent Robots − Robots are able to perform the tasks given by a human. They have
sensors to detect physical data from the real world such as light, heat, temperature,
movement, sound, bump, and pressure. They have efficient processors, multiple sensors
and huge memory, to exhibit intelligence. In addition, they are capable of learning from
their mistakes and they can adapt to the new environment.
PRACTICAL NO.2
AIM: -Implementation of Depth-First Search(DFS).
2.5 Program: -
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
void main()
{
int m;
clrscr();
cout<<"Enter of vertices";
cin>>n;
cout<<"Enter of edges";
cin>>m;
cout<<"EDGES\n";
for(k=1;k<=m;k++)
{
cin>>i>>j;
cost[i][j]=1;
}
cout<<"Enter initial vertex";
cin>>v;
cout<<"Order of Visited vertices\n";
cout<<v<<" ";
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0&& visited[j]!=1&& visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;}
v=stk[--top];
cout<<v<<" ";
k++;
visit[v]=0;
visited[v]=1;
}
getch();
}
Output:-
Fig. 2.1
PRACTICAL NO. 3
AIM: -Write a program to implement towers of Hanoi
Fig.3.1
PRACTICAL NO. 4
AIM: -Write a program to implement water jug problem.
‘i’ represents the number of liters of water in the 4-liter jug and ‘j’ represents the number of
liters of water in the 3-liter jug. The initial state is ( 0,0) that is no water on each jug. The
goal state is to get ( 2,n) for any value of ‘n’.
To solve this we have to make some assumptions not mentioned in the problem. They are
1. We can fill a jug from the pump.
2. We can pour water out of a jug to the ground.
3. We can pour water from one jug to another.
4. There is no measuring device available.
4.2 Program: -
#include<iostream.h>
#include<iomanip.h>
#include<math.h>
#include<conio.h>
int xcapacity;
int ycapacity;
void display(int a, int b,int s);
int min(int d, int f)
{if (d < f)
return d;
else
return f;
} int steps(int n)
{
int x = 0, y = 0, step = 0;
int temp;
cout << setw(55) << “ Vessel A Vessel B Steps” << endl; while
(x != n )
{if (x == 0)
{ x = xcapacity;
step += 1;
cout << “Fill X “; display(x, y,step);
} else if (y ==
ycapacity) { y = 0;
step++;
cout << “Empty Y “; display(x, y,step);
}else {
temp = min(ycapacity – y, x);
y = y + temp;
x = x – temp;
step++;
cout << “Pour X in Y”; display(x, y, step);
}}
return step;
}void display(int a, int b,int s)
{cout << setw(16) << a << setw(15) << b << setw(15)<<s<<endl;
} void main()
{
int n, ans;
clrscr();
Output:-
Fig.4.1
PRACTICAL NO. 5
(Method 1)
AIM: -Write a program to implement tic tac toe game for 0 and X.
Fig.5.1
5.3 Program: -
#include<stdio.
h>
#include<conio
.h>
#include<stdlib
.h>
#include<iostre
am.h>
char matrix[3][3]; //intitial matrix
declaration char check(void); //
declaration of functions void
init_matrix(void);
void
get_player_move(void);
void
get_computer_move(void
); void disp_matrix(void);
int main(void)
{
clrscr();
char done;
cout<<"Human vs. AI Tic Tac Toe."<<endl;
cout<<"You will be playing against the
computer as 'X'"<<endl; done = ' ';
init_ma
trix();
do {
disp_m
atrix();
get_player_move();
done = check(); /* check winner */
if(done!= ' ') break; /* if winner
found...*/ get_computer_move();
done = check(); /* check for winner again */
} while(done== ' '); if(done=='X')
cout<<"Human won! (but AI very dumb anyway)\n"; else
cout<<"AI so stupid still can win against you..."<<endl; disp_matrix();
/* show final positions */
return 0;
}
void init_matrix(void) //matrix intitialisation
{
int i, j;
for(i=0; i<3; i++)
for(j=0; j<3; j++) matrix[i][j] = ' ';
}
void get_player_move(void) //call function for player input
{
int x, y;
cout<<"Enter X,Y coordinates for your move:
"; scanf("%d%*c%d", &x, &y);
x--; y--;
if(matrix[x][y]!= ' ')
{
cout<<"Invalid move, try
again.\n";
get_player_move();
}
else matrix[x][y] = 'X';
}
void get_computer_move(void) //AI move input
{
int i, j;
for(i=0; i<3; i++)
{
for(j=0;j<3; j++)
if(matrix[i][j]==' ')
break;
if(matrix[i][j]==' ') break;
}
if(i*j==9)
{
cout<<"dr
aw\n";
exit(0);
}
else
matrix[i][j] = 'O';
}
void disp_matrix(void) //matrix display
{
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) //used for identifying winner
{ int i;
for(i=0; i<3; i++) /* check rows */
if(matrix[i][0]==matrix[i][1] &&
matrix[i][0]==matrix[i][2]) return
matrix[i][0]; for(i=0; i<3; i++) /* check
columns */ if(matrix[0][i]==matrix[1][i]
&& matrix[0][i]==matrix[2][i]) return
matrix[0][i];
/* test diagonals */
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:
Fig. 5.2
Method 2
Write a program to implement Tic-Tac-Toe game problem
#include <iostream>
#include <stdlib.h>
//Variable Declaration
int choice;
int row,column;
void display_board(){
cout<<"tt | | n";
cout<<"tt_____|_____|_____n";
cout<<"tt | | n";
cout<<"tt_____|_____|_____n";
cout<<"tt | | n";
cout<<"tt | | n";
void player_turn(){
if(turn == 'X'){
}
else if(turn == 'O'){
//updating the board according to choice and reassigning the turn Start
cin>> choice;
switch(choice){
default:
cout<<"Invalid Move";
board[row][column] = 'X';
turn = 'O';
board[row][column] = 'O';
turn = 'X';
}else {
player_turn();
/* Ends */
display_board();
//Function to get the game status e.g. GAME WON, GAME DRAW GAME IN CONTINUE MODE
bool gameover(){
return false;
return false;
return true;
//Checking the if game already draw
draw = true;
return false;
int main()
cout<<"tttT I C K -- T A C -- T O E -- G A M Ettt";
cout<<"nttttFOR 2 PLAYERSnttt";
while(gameover()){
display_board();
player_turn();
gameover();
else
cout<<"nnGAME DRAW!!!nn";
PRACTICAL NO.6
AIM: -Write a program to implement production system.
6.1 Production System:
Search forms the core of many intelligent processes, it is useful to structure AI
programs in a way that facilitates describing and performing the search process.
Production system provides such structures .In other words the process of solving the
problem can usefully be modeled as production system.
The goal database is the central data structure used by an AI production system. The
production system. The production rules operate on the global database. Each rule has
a precondition that is either satisfied or not by the database. If the precondition is
satisfied, the rule can be applied. Application of the rule changes the database. The
control system chooses which applicable rule should be applied and ceases
computation when a termination condition on the database is satisfied. If several rules
are to fire at the same time, the control system resolves the conflicts.
6.2 Components of production system
o A set of rules of the form Ci → Ai where Ci is the condition part and Ai is the action
part. The condition determines when a given rule is applied, and the action
determines what happens when it is applied.
o One or more knowledge databases that contain whatever information is relevant
for the given problem. Some parts of the database may be permanent, while
others may temporary and only exist during the solution of the current problem. The
information in the databases may be structured in any appropriate manner.
o A control strategy that determines the order in which the rules are applied to the
database, and provides a way of resolving any conflicts that can arise when several
rules match at once.
o A rule applier which is the computational system that implements the control
strategy and applies the rules.
6.3 Four classes of production systems:-
1. A monotonic production system
2. A non monotonic production system
3. A partially commutative production system
4. A commutative production system.
6.4 Advantages of production systems:-
1. Production systems provide an excellent tool for structuring AI programs.
2. Production Systems are highly modular because the individual rules can be
added, removed or modified independently.
3. The production rules are expressed in a natural form, so the statements
contained in the knowledge base should the a recording of an expert thinking out
loud.
6.5 Disadvantages of Production Systems:-
1. One important disadvantage is the fact that it may be very difficult analyse the
flow of control within a production system because the individual rules don’t call
each other.
2. Production systems describe the operations that can be performed in a search for
a solution to the problem. They can be classified as follows.
6.6 Program
#include<iostr
eam.h>
#include<conio
.h> int main()
{
char
answe
r;
clrscr
();
cout<<"Answer the following question to determine whether JOHN should get
scholarship or not?"<<endl;
cout<<"Q1) Is John a Student?
(y/n)\n"; cin>>answer;
if(answer=='y'){
cout<<"John enjoys Student Life"<<endl;
cout<<"John Enjoys Student Life --> John Meets
Friends"<<endl; cout<<"John Enjoys Meets Friends -->
John Needs Money"<<endl; cout<<"Q2) Does John has a
job?(y/n)";
cin>>an
swer;
if(answ
er=='y')
{
cout<<"John Has Job --> John Has Free Time"<<endl;
cout<<"Since John Works in Free Time--> John Is Not Not Good In Studies
"<<endl; cout<<"John should not get the scholarship";
}
}
else
cout<<"John Will not recieve scholarship as he is not a
student"<<endl; return 0;
}
Output
PRACTICAL NO.7
#include <cstdio>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
// x and y are the amounts of water in litres in the two jugs respectively
struct state {
int x, y;
};
queue <state> q;
// Mapping from a state to its parent state and rule no. that
q.push(start);
while (!q.empty()) {
q.pop();
goal = top;
break;
// Consider this state for visiting only if it has not been visited before
if (parentOf.find(child) == parentOf.end()) {
q.push(child);
if (parentOf.find(child) == parentOf.end()) {
q.push(child);
if (top.x > 0) {
if (parentOf.find(child) == parentOf.end()) {
q.push(child);
if (top.y > 0) {
if (parentOf.find(child) == parentOf.end()) {
q.push(child);
// Pour water from the second jug into the first jug until the first jug is full
// or the second jug is empty
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()) {
q.push(child);
// Pour water from the first jug into the second jug until the second jug is full
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()) {
q.push(child);
} } }
return;
path.push(make_pair(goal, 0));
while (parentOf[path.top().first].second != 0)
path.push(parentOf[path.top().first]);}
int main() {
scanf("%d", &target);
if (path.empty())
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()) {
path.pop();
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; }
PRACTICAL NO.8
#include <stack>
#include <map>
#include <algorithm>
// x and y are the amounts of water in litres in the two jugs respectively
struct state {
int x, y;
} };
stack <state> s;
// Mapping from a state to its parent state and rule no. that
// led to this state
s.push(start);
while (!s.empty()) {
s.pop();
goal = top;
break; }
// This step uses production rules to produce successors of the current state
// 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) {
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
if (top.y > 0) {
if (parentOf.find(child) == parentOf.end()) {
s.push(child);
// Pour water from the second jug into the first jug until the first jug is full
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);
// Pour water from the first jug into the second jug until the second jug is full
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);
return;
path.push(make_pair(goal, 0));
while (parentOf[path.top().first].second != 0)
path.push(parentOf[path.top().first]);}
int main() {
scanf("%d", &target);
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()) {
path.pop();
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);
#include <stdio.h>
printf("\n"); }}
int i, j;
if (board[row][i])
return false;
if (board[i][j])
return false;
if (board[i][j])
return false;
return true;}
return true;
if (isSafe(board, i, col)) {
board[i][col] = 1;
return true;
board[i][col] = 0; // BACKTRACK } }
return false;}
bool solveNQ() {
int board[N][N] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
return false; }
printSolution(board);
return true;}
int main() {
solveNQ();
return 0;}
PRACTICAL NO.10
#define ROW 9
#define COL 10
typedef pair < double, pair < int, int >> pPair;
struct cell {
double f, g, h;
};
if (grid[row][col] == 1)
return (true);
else
return (false);
return (true);
else
return (false);
}
void tracePath(cell cellDetails[][COL], Pair dest) {
cellDetails[row][col].parent_j == col)) {
Path.push(make_pair(row, col));
row = temp_row;
col = temp_col;
Path.push(make_pair(row, col));
while (!Path.empty()) {
Path.pop();
return;
printf("Source is invalid\n");
return;
return;
return;
return;
bool closedList[ROW][COL];
cell cellDetails[ROW][COL];
int i, 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;
while (!openList.empty()) {
pPair p = * openList.begin();
openList.erase(openList.begin());
i = p.second.first;
j = p.second.second;
closedList[i][j] = true;
if (isValid(i - 1, j) == true) {
cellDetails[i - 1][j].parent_i = i;
cellDetails[i - 1][j].parent_j = j;
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i - 1, j) == true) {
openList.insert(make_pair(fNew,
make_pair(i - 1, j)));
cellDetails[i - 1][j].parent_i = i;
cellDetails[i - 1][j].parent_j = j;
if (isValid(i + 1, j) == true) {
// current successor
cellDetails[i + 1][j].parent_i = i;
cellDetails[i + 1][j].parent_j = j;
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i + 1, j) == true) {
cellDetails[i + 1][j].parent_i = i;
cellDetails[i + 1][j].parent_j = j;
if (isValid(i, j + 1) == true) {
cellDetails[i][j + 1].parent_i = i;
cellDetails[i][j + 1].parent_j = j;
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i, j + 1) == true) {
openList.insert(make_pair(fNew,
make_pair(i, j + 1)));
cellDetails[i][j + 1].parent_i = i;
cellDetails[i][j + 1].parent_j = j;
if (isValid(i, j - 1) == true) {
cellDetails[i][j - 1].parent_i = i;
cellDetails[i][j - 1].parent_j = j;
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i, j - 1) == true) {
openList.insert(make_pair(fNew,
make_pair(i, j - 1)));
cellDetails[i][j - 1].parent_i = i;
cellDetails[i][j - 1].parent_j = j;
if (isValid(i - 1, j + 1) == true) {
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i - 1, j + 1) == true) {
openList.insert(make_pair(fNew,
make_pair(i - 1, j + 1)));
if (isValid(i - 1, j - 1) == true) {
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i - 1, j - 1) == true) {
if (isValid(i + 1, j + 1) == true) {
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i + 1, j + 1) == true) {
make_pair(i + 1, j + 1)));
if (isValid(i + 1, j - 1) == true) {
tracePath(cellDetails, dest);
foundDest = true;
return;
isUnBlocked(grid, i + 1, j - 1) == true) {
make_pair(i + 1, j - 1)));
if (foundDest == false)
return;
int main() {
int grid[ROW][COL] =
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 }
};
return (0);
PRACTICAL NO.11
#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;
do {
disp_matrix();
get_player_move();
get_computer_move();
return 0;
void init_matrix(void) {
int i, j;
void get_player_move(void) {
int x, y;
y--;
get_player_move();
void get_computer_move(void) {
int i, j;
if (i * j == 9) {
printf("draw\n");
exit(0);
} else
matrix[i][j] = 'O';
int t;
matrix[t][1], matrix[t][2]);
if (t != 2) printf("\n---|---|---\n");
printf("\n");
char check(void) {
int i;
/* test diagonals */
matrix[1][1] == matrix[2][2])
return matrix[0][0];
matrix[1][1] == matrix[2][0])
return matrix[0][2];
PRACTICAL NO.12
#define N 3
struct Node {
Node * parent;
int mat[N][N];
int x, y;
int cost;
int level;
};
printf("\n");
return node;
int count = 0;
count++;
return count;
if (root == NULL)
return;
printf("\n");
}
struct comp {
return (lhs -> cost + lhs -> level) > (rhs -> cost + rhs -> level);
};
int final[N][N]) {
priority_queue < Node * , std::vector < Node * > , comp > pq;
pq.push(root);
while (!pq.empty()) {
pq.pop();
printPath(min);
return;
int main() {
int initial[N][N] = {
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};
int final[N][N] = {
{1, 2, 3},
{5, 8, 6},
{0, 7, 4}
};
int x = 1, y = 2;
solve(initial, x, y, final);
return 0;
}
PRACTICAL NO.13
void takeInput() {
int i, j;
completed[i] = 0;
printf("\n");
printf("\t%d", ary[i][j]);
int i, ncity;
completed[city] = 1;
if (ncity == 999) {
ncity = 0;
cost += ary[city][ncity];
return;
mincost(ncity);
int least(int c) {
int i, nc = 999;
kmin = ary[c][i];
nc = i;
if (min != 999)
cost += kmin;
return nc;
int main() {
takeInput();
return 0;
https://gtupractical.com/artificial-intelligence-practical/