Anda di halaman 1dari 72

Subject:

Artificial Intelligence

LAB MANUAL
INDEX

Page Faculty
No. Date Experiment Description
No. Sign

Write a program to implement Tic-Tac-


1
Toe game problem

2 Write a program to implement BFS

3 Write a program to implement DFS

Write a program to implement Single


4 Player Game

Write a program to Implement A*


5
Algorithm
Write a program to Implement AO*
6 Algorithm

Write a program to solve N-Queens


7
problem using Prolog.
Write a program for the following
task:Create a suitable database and then
find the following
8 •Students who are living in Rajkot
•Age Greater Than 15
•Students who has more than 60%
Write a program to solve 8 puzzle problem
9
using Prolog.

Write a program to check whether given


10
value is character or digit

Abhi Khanpara (91600103021)


Write a program to generate
11 random number with respect to
entered digit.
Write a program to implement
12
login system.
Write a program to implement
13
login system recursively
Write a program to solve
14
travelling salesman problem.
Write a program to display the
15
element of give list.
Write a program for the family
16
tree.
Write a program to check given
17
element is in the list or not.
Write a program to print the last
19
element of the list
Write a program to print the sum
20
of the elements of the given list
22 Write a programme for File.

Abhi Khanpara (91600103021)


Experiment 1:
Aim : Write a program to implement Tic-Tac-Toe game problem.
Program:
#include <iostream>
using namespace std;

char square[10] = {'o','1','2','3','4','5','6','7','8','9'};

int checkwin();
void board();

int main()
{
int player = 1,i,choice;

char mark;
do
{
board();
player=(player%2)?1:2;

cout << "Player " << player << ", enter a number: ";
cin >> choice;

mark=(player == 1) ? 'X' : 'O';

if (choice == 1 && square[1] == '1')

Abhi Khanpara (91600103021)


square[1] = mark;
else if (choice == 2 && square[2] == '2')

square[2] = mark;
else if (choice == 3 && square[3] == '3')

square[3] = mark;
else if (choice == 4 && square[4] == '4')

square[4] = mark;
else if (choice == 5 && square[5] == '5')

square[5] = mark;
else if (choice == 6 && square[6] == '6')

square[6] = mark;
else if (choice == 7 && square[7] == '7')

square[7] = mark;
else if (choice == 8 && square[8] == '8')

square[8] = mark;
else if (choice == 9 && square[9] == '9')

square[9] = mark;
else
{
Abhi Khanpara (91600103021)
cout<<"Invalid move ";

player--;
cin.ignore();
cin.get();
}
i=checkwin();

player++;
}while(i==-1);
board();
if(i==1)

cout<<"==>\aPlayer "<<--player<<" win ";


else
cout<<"==>\aGame draw";

cin.ignore();
cin.get();
return 0;
}

int checkwin()
{
if (square[1] == square[2] && square[2] == square[3])

Abhi Khanpara (91600103021)


return 1;
else if (square[4] == square[5] && square[5] == square[6])

return 1;
else if (square[7] == square[8] && square[8] == square[9])

return 1;
else if (square[1] == square[4] && square[4] == square[7])

return 1;
else if (square[2] == square[5] && square[5] == square[8])

return 1;
else if (square[3] == square[6] && square[6] == square[9])

return 1;
else if (square[1] == square[5] && square[5] == square[9])

return 1;
else if (square[3] == square[5] && square[5] == square[7])

return 1;
else if (square[1] != '1' && square[2] != '2' && square[3] != '3'
&& square[4] != '4' && square[5] != '5' && square[6] != '6'
&& square[7] != '7' && square[8] != '8' && square[9] != '9')

return 0;
else
Abhi Khanpara (91600103021)
return -1;
}

void board()
{

cout << "\n\n\tTic Tac Toe\n\n";

cout << "Player 1 (X) - Player 2 (O)" << endl << endl;
cout << endl;

cout << " | | " << endl;


cout << " " << square[1] << " | " << square[2] << " | " << square[3] << endl;

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


cout << " | | " << endl;

cout << " " << square[4] << " | " << square[5] << " | " << square[6] << endl;

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


cout << " | | " << endl;

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

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


}

Abhi Khanpara (91600103021)


Output:

Abhi Khanpara (91600103021)


Experiment : 2
Aim : Write a program to implement BFS (for 8 puzzle problem or Water Jug
problem or any AI search problem
Program:
#include<stdio.h>
#include<conio.h>
struct node
{
int x, y;
struct node *next;
}*root, *left, *right;

int isNodePresent(struct node *next, int jug1, int jug2, int f1, int f2)
{
struct node *temp;
if((next->x == f1) && (next->y == f2)){
return(0);
}
if((next->x == jug1) && (next->y == jug2)){
return(1);
}
if((next->x == 0) && (next->y == 0)){
return(1);
}
Abhi Khanpara (91600103021)
temp = left;
while(1)
{
if((temp->x == next->x) && (temp->y == next->y)){
return(1);
}
else if(temp->next == NULL){
break;
}
else{
temp = temp->next;
}
}
temp = right;
while(1)
{
if((temp->x == next->x) && (temp->y == next->y)){
return(1);
}
else if(temp->next == NULL){
break;
}
temp = temp->next;
}
return(0);
Abhi Khanpara (91600103021)
}

void bfstree(int jug1, int jug2, int f1, int f2)


{
int flag1, flag2;
struct node *tempLeft, *tempRight;
root = (struct node*)malloc(sizeof(struct node));
root->x = 0; root->y = 0; root->next = NULL;
left = (struct node*)malloc(sizeof(struct node));
left->x = 0; left->y = jug2; left->next = NULL;
right = (struct node*)malloc(sizeof(struct node));
right->x = jug1; right->y = 0; right->next = NULL;
tempLeft = left;
tempRight = right;
while(1)
{
flag1 = 0; flag2 = 0;
if((tempLeft->x != f1) || (tempLeft->y != f2)) {
tempLeft->next = genNewState(tempLeft, jug1, jug2, f1, f2);
tempLeft = tempLeft->next;
tempLeft->next = NULL;
flag1 = 1;
}
if((tempRight->x != f1) || (tempRight->y != f2)) {
tempRight->next = genNewState(tempRight, jug1, jug2, f1, f2);
Abhi Khanpara (91600103021)
tempRight = tempRight->next;
tempRight->next = NULL;
flag2 = 1;
}
if((flag1 == 0) && (flag2 == 0)){
break;
}
}
}
struct node* genNewState(struct node *current, int jug1, int jug2, int f1, int f2)
{
int d;
struct node *next;
next = (struct node*)malloc(sizeof(struct node));
next->x = jug1;
next->y = current->y;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
next->x = current->x;
next->y = jug2;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
next->x = 0;
Abhi Khanpara (91600103021)
next->y = current->y;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
next->y = 0;
next->x = current->x;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1) {
return(next);
}
if((current->y < jug2) && (current->x != 0)) {
d = jug2 - current->y;
if(d >= current->x) {
next->x = 0;
next->y = current->y + current->x;
} else {
next->x = current->x - d;
next->y = current->y + d;
}
if(isNodePresent(next, jug1, jug2, f1, f2) != 1) {
return(next);
}
}
if((current->x < jug1) && (current->y != 0)) {
d = jug1 - current->x;
if(d >= current->y) {
Abhi Khanpara (91600103021)
next->y = 0;
next->x = current->x + current->y;
}
else
{
next->y = current->y - d;
next->x = current->x + d;
}
if(isNodePresent(next, jug1, jug2, f1, f2) != 1) {
return(next);
}
}
return(NULL);
}

void BFS(int f1, int f2)


{
struct node *temp1 = left, *temp2 = right;
printf("\nSoultion : \n");
printf("(%d , %d)\n", root->x, root->y);
while(1)
{
printf("(%d , %d)\n", temp1->x, temp1->y);
if((temp1->x == f1)&&(temp1->y == f2)){
break;
Abhi Khanpara (91600103021)
}
temp1 = temp1->next;
printf("(%d , %d)\n", temp2->x, temp2->y);
if((temp2->x == f1)&&(temp2->y == f2)){
break;
}
temp2 = temp2->next;
}
}
void main()
{
int jug1, jug2, f1, f2;
clrscr();
printf("Enter the Capacity of jug1 : ");
scanf("%d", &jug1);
printf("Enter the Capacity of jug2 : ");
scanf("%d", &jug2);
printf("\nRequired Water in jug1 : ");
scanf("%d", &f1);
printf("Required Water in jug2 : ");
scanf("%d", &f2);
bfstree(jug1, jug2, f1, f2);
BFS(f1, f2);
getch();
}
Abhi Khanpara (91600103021)
Output:

Abhi Khanpara (91600103021)


Experiment : 3
Aim : Write a program to implement DFS (for 8 puzzle problem or Water Jug
problem or any AI search problem).
Program:

#include<stdio.h>
#include<conio.h>
struct node
{
int x, y;
struct node *next;
}*root, *left, *right;

void main()
{
int jug1, jug2, f1, f2;
clrscr();
printf("Capacity of jug1 : ");
scanf("%d", &jug1);
printf("Capacity of jug2 : ");
scanf("%d", &jug2);
printf("Required water in jug1 : ");
scanf("%d", &f1);
printf("Required water in jug2 : ");

Abhi Khanpara (91600103021)


scanf("%d", &f2);
generateTree(jug1, jug2, f1, f2);
DFS();
getch();
}
int isNodePresent(struct node *next, int jug1, int jug2, int f1, int f2)
{
struct node *temp;
if((next->x == f1) && (next->y == f2)){
return(0);
}
if((next->x == jug1) && (next->y == jug2)){
return(1);
}
if((next->x == 0) && (next->y == 0)){
return(1);
}
temp = left;
while(1)
{
if((temp->x == next->x) && (temp->y == next->y)){
return(1);
}
Abhi Khanpara (91600103021)
else if(temp->next == NULL){
break;
} else {
temp = temp->next;
}
}
temp = right;
while(1)
{
if((temp->x == next->x) && (temp->y == next->y)){
return(1);
} else if(temp->next == NULL){
break;
}
temp = temp->next;
}
return(0);
}
void DFS()
{
struct node *temp;
temp = left;
printf("Start State : (%d,%d)\n", root->x, root->y);
Abhi Khanpara (91600103021)
printf("Solution : \n");
while(1)
{
printf("(%d,%d)\n", temp->x, temp->y);
if(temp->next == NULL){
break;
}
temp = temp->next;
}
temp = right;
}

struct node* genNewState(struct node *current, int jug1, int jug2, int f1,
int f2)
{
int d;
struct node *next;
next = (struct node*)malloc(sizeof(struct node));
next->x = jug1;
next->y = current->y;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
Abhi Khanpara (91600103021)
next->x = current->x;
next->y = jug2;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
next->x = 0;
next->y = current->y;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
next->y = 0;
next->x = current->x;
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
if((current->y < jug2) && (current->x != 0))
{
d = jug2 - current->y;
if(d >= current->x)
{
next->x = 0;
next->y = current->y + current->x;
} else {
Abhi Khanpara (91600103021)
next->x = current->x - d;
next->y = current->y + d;
}
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
}
if((current->x < jug1) && (current->y != 0))
{
d = jug1 - current->x;
if(d >= current->y) {
next->y = 0;
next->x = current->x + current->y;
} else {
next->y = current->y - d;
next->x = current->x + d;
}
if(isNodePresent(next, jug1, jug2, f1, f2) != 1){
return(next);
}
}
return(NULL);
}
Abhi Khanpara (91600103021)
void generateTree(int jug1, int jug2, int f1, int f2)
{
int flag1, flag2;
struct node *tempLeft, *tempRight;
root = (struct node*)malloc(sizeof(struct node));
root->x = 0; root->y = 0; root->next = NULL;
left = (struct node*)malloc(sizeof(struct node));
left->x = 0; left->y = jug2; left->next = NULL;
right = (struct node*)malloc(sizeof(struct node));
right->x = jug1; right->y = 0; right->next = NULL;
tempLeft = left;
tempRight = right;
while(1)
{
flag1 = 0; flag2 = 0;
if((tempLeft->x != f1) || (tempLeft->y != f2))
{
tempLeft->next = genNewState(tempLeft, jug1, jug2, f1, f2);
tempLeft = tempLeft->next;
tempLeft->next = NULL;
flag1 = 1;
}
if((tempRight->x != f1) || (tempRight->y != f2))
Abhi Khanpara (91600103021)
{
tempRight->next = genNewState(tempRight, jug1, jug2, f1, f2);
tempRight = tempRight->next;
tempRight->next = NULL;
flag2 = 1;
}
if((flag1 == 0) && (flag2 == 0))
break;
}
}

Output:

Abhi Khanpara (91600103021)


Experiment : 4
Aim : Write a program to implement Single Player Game (Using Heuristic
Function)
Program:
#include <bits/stdc++.h>
using namespace std;
#define V 4

// implementation of traveling Salesman Problem


int travllingSalesmanProblem(int graph[][V], int s)
{
// store all vertex apart from source vertex
vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);

// store minimum weight Hamiltonian Cycle.


int min_path = INT_MAX;
do {

// store current Path weight(cost)


int current_pathweight = 0;
Abhi Khanpara (91600103021)
// compute current path weight
int k = s;
for (int i = 0; i < vertex.size(); i++) {
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];

// update minimum
min_path = min(min_path, current_pathweight);

} while (next_permutation(vertex.begin(), vertex.end()));

return min_path;
}

// driver program to test above function


int main()
{
// matrix representation of graph
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
Abhi Khanpara (91600103021)
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int s = 0;
cout <<"Cost = "<< travllingSalesmanProblem(graph, s) << endl;
return 0;
}

Output:

Abhi Khanpara (91600103021)


Experiment : 5
Aim : Write a program to Implement A* Algorithm
Program :

#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);
Abhi Khanpara (91600103021)
}
double calculateHValue(int row, int col, Pair dest)
{
return ((double)sqrt ((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;
}

Abhi Khanpara (91600103021)


if (isValid (dest.first, dest.second) == false)
{
printf ("Destination is invalid\n");
return;
}

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;

Abhi Khanpara (91600103021)


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

Abhi Khanpara (91600103021)


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

//----------- 2nd Successor (South) ------------

if (isValid(i+1, j) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i+1, j, dest) == true)
{
// Set the Parent of the destination cell
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;

Abhi Khanpara (91600103021)


}
}
}

//----------- 3rd Successor (East) ------------

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

//----------- 4th Successor (West) ------------

Abhi Khanpara (91600103021)


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

// Update the details of this cell


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

//----------- 5th Successor (North-East) ------------

if (isValid(i-1, j+1) == true)


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

Abhi Khanpara (91600103021)


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

//----------- 6th Successor (North-West) ------------

if (isValid (i-1, j-1) == true)


{

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


{

cellDetails[i-1][j-1].parent_i = i;

Abhi Khanpara (91600103021)


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)));
// Update the details of this cell
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;
}
}
}

//----------- 7th Successor (South-East) ------------

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;

Abhi Khanpara (91600103021)


}

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

//----------- 8th Successor (South-West) ------------

if (isValid (i+1, j-1) == true)


{

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


{
// Set the Parent of the destination cell
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 &&

Abhi Khanpara (91600103021)


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()
{
/* Description of the Grid-
1--> The cell is not blocked
0--> The cell is blocked */
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 },

Abhi Khanpara (91600103021)


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

Abhi Khanpara (91600103021)


Experiment – 7
Aim : Write a program to solve N-Queens problem using Prolog.
Program :
/* C/C++ program to solve N Queen Problem using
backtracking */
#define N 4
#include <stdbool.h>
#include <stdio.h>
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
}
bool isSafe(int board[N][N], int row, int col)
{
int i, j;

/* Check this row on left side */


for (i = 0; i < col; i++)
if (board[row][i])
return false;

Abhi Khanpara (91600103021)


/* Check upper diagonal on left side */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;

return true;
}
bool solveNQUtil(int board[N][N], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, 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 },
Abhi Khanpara (91600103021)
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
int main()
{
solveNQ();
return 0;
}

Output :

Abhi Khanpara (91600103021)


Experiment : 8
Aim : Write a program for the following task:Create a suitable database
and then find the following
•Students who are living in Rajkot
•Age Greater Than 15
•Students who has more than 60%

Program :
package jdbc;
import java.sql.*;
public class JDBC{
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from detail where city='Rajkot' and
marks>=60 and Age>=15");
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getInt(3)+"
"+rs.getInt(4));
}
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}

Abhi Khanpara (91600103021)


Output :

Database :

Abhi Khanpara (91600103021)


Experiment : 9
Aim : Write a program to solve 8 puzzle problem using Prolog.
Program :
#include <bits/stdc++.h>
using namespace std;
#define N 3
struct Node
{
Node* parent;
int mat[N][N];
int x, y;
int cost;
int level;
};
int printMatrix(int mat[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
}
Node* newNode(int mat[N][N], int x, int y, int newX,
int newY, int level, Node* parent)
{

Abhi Khanpara (91600103021)


Node* node = new Node;
node->parent = parent;
memcpy(node->mat, mat, sizeof node->mat);
swap(node->mat[x][y], node->mat[newX][newY]);
node->cost = INT_MAX;
node->level = level;
node->x = newX;
node->y = newY;
return node;
}
int row[] = { 1, 0, -1, 0 };
int col[] = { 0, -1, 0, 1 };
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;
}
int isSafe(int x, int y)
{
return (x >= 0 && x < N && y >= 0 && y < N);
}
void printPath(Node* root)
{
if (root == NULL)
Abhi Khanpara (91600103021)
return;
printPath(root->parent);
printMatrix(root->mat);

printf("\n");
}
struct comp
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return (lhs->cost + lhs->level) > (rhs->cost + rhs->level);
}
};
void solve(int initial[N][N], int x, int y,
int final[N][N])
{
priority_queue<Node*, std::vector<Node*>, comp> pq;
Node* root = newNode(initial, x, y, x, y, 0, NULL);
root->cost = calculateCost(initial, final);
pq.push(root);
while (!pq.empty())
{
Node* min = pq.top();
pq.pop();
if (min->cost == 0)
{
printPath(min);
return;
Abhi Khanpara (91600103021)
}
for (int i = 0; i < 4; i++)
{
if (isSafe(min->x + row[i], min->y + col[i]))
{
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);
pq.push(child);
}
}
}
}
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}
Abhi Khanpara (91600103021)
};
int x = 1, y = 2;
solve(initial, x, y, final);
return 0;
}

Output :

Abhi Khanpara (91600103021)


Experiment : 10
Aim : Write a program to check whether given value is character or digit

Program :
#include <stdio.h>
int main()
{
char ch;
/* Input character from user */
printf("Enter any character: ");
scanf("%c", &ch);
/* Alphabet check */
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("'%c' is alphabet.", ch);
}
else if(ch >= '0' && ch <= '9')
{
printf("'%c' is digit.", ch);
}
else
{
printf("'%c' is special character.", ch);
}
return 0;
}

Abhi Khanpara (91600103021)


Output :

Abhi Khanpara (91600103021)


Experiment : 11
Aim : Write a program to generate random number with respect to entered
digit.

Program :
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
unsigned long long int randm(int n);
unsigned long long int von(unsigned long long int x, int n);
int main(void)
{
unsigned long long int x, s;
int n, i, r;
printf("Enter the number of digits in the seed value ");
scanf("%d", &n);
printf("\nEnter the total number of random numbers to be generated ");
scanf("%d", &r);
if (n >= 12){
printf("TOO LARGE!!");
exit(0);
}
x = randm(n);
for(i = 0; i < r; i++){
s = von(x, n);
x = s;
printf("\nRandom Number generated: %lld\n", s);
}
return 0;
}
unsigned long long int randm(int n)
{
double x;
unsigned long long int y;
srand(getpid());
Abhi Khanpara (91600103021)
x = rand() / (double)RAND_MAX;
y = (unsigned long long int) (x * pow(10.0, n*1.0));
return y;
}
unsigned long long int von(unsigned long long int x, int n)
{
unsigned long long int y;
int k;
k = n / 2;
y =(unsigned long long int)((x / pow(10.0, k * 1.0)) * x) % (unsigned long long int) (pow(10.0,
n * 1.0));
return y;
}

Output :

Abhi Khanpara (91600103021)


Experiment : 12
Aim: Write a program to implement login system.
Program:
#include <stdio.h>
#include <string.h>
#include <conio.h>
//created by chaitanya
int main()
{
char username[15];
char password[12];

printf("Enter your username:\n");


scanf("%s",&username);

printf("Enter your password:\n");


scanf("%s",&password);

if(strcmp(username,"chaitu")==0){
if(strcmp(password,"123")==0){

printf("\nWelcome.Login Success!");
Abhi Khanpara (91600103021)
}else{
printf("\nwrong password");
}
}else{
printf("\nUser doesn't exist");
}
return 0;
}

Output:

Abhi Khanpara (91600103021)


Experiment : 13
Aim: Write a program to implement login system recursively.
Program:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>

using namespace std;

void mainmenu();

int choice;
bool cinfail;
int confirmation;
string username, password, password2;

void writetofile(string username){


ofstream writefile;
string file = username+".txt";
writefile.open(file.c_str());
writefile << password;
writefile.close();
mainmenu(); }

void login(){
cout << "You are being logged in!";}

void registerpassword(){
cout << "Please enter the password:" << endl;
cin >> password;
cout << "Please renter your password:" << endl;
cin >> password2;
if (password == password2){
cin.clear();
cin.ignore(10000,'\n');
writetofile(username);
exit(1);

Abhi Khanpara (91600103021)


}
else;{
cout << "Sorry invalid" << endl;
registerpassword();
}}

void registerme(){
cout << "Please enter your username: " << endl;
getline(cin, username);
cout << "\nUsername - \""<< username << "\"\nConfirm? \n\n[1] Yes\n[2] No" << endl;
cin >> confirmation;
if (confirmation == 1){
registerpassword();
}

else; {
cout << "Sorry invalid input, Please try again" << endl;
cin.clear();
cin.ignore(10000,'\n');
registerme();
}}

void exit(){
exit(0);}

void mainmenu(){ cout << "Hello, Would you like to log in or register\n[1] Login\n[2]
Register\n[3] Exit" <<endl; cin >> choice; do{
cinfail = cin.fail();
cin.clear();
cin.ignore(10000,'\n');

}while(cinfail == true);{
switch(choice){
case 1:
login();
break;

case 2:
registerme();
break;

case 3:
exit();}}}

Abhi Khanpara (91600103021)


main(){
mainmenu();
}

Output:

Abhi Khanpara (91600103021)


Experiment – 14
Aim : Write a program to solve travelling salesman problem.
Program :
#include<stdio.h>

int ary[10][10],completed[10],n,cost=0;

void takeInput()
{
int i,j;

printf("Enter the number of villages: ");


scanf("%d",&n);

printf("\nEnter the Cost Matrix\n");

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


{
printf("\nEnter Elements of Row: %d\n",i+1);

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


scanf("%d",&ary[i][j]);

completed[i]=0;
}

printf("\n\nThe cost list is:");

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


{
printf("\n");

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


printf("\t%d",ary[i][j]);
}
}

void mincost(int city)


{
int i,ncity;

completed[city]=1;

Abhi Khanpara (91600103021)


printf("%d--->",city+1);
ncity=least(city);

if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];

return;
}

mincost(ncity);
}

int least(int c)
{
int i,nc=999;
int min=999,kmin;

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


{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}

if(min!=999)
cost+=kmin;

return nc;
}

int main()
{
takeInput();

printf("\n\nThe Path is:\n");


mincost(0); //passing 0 because starting vertex

printf("\n\nMinimum cost is %d\n ",cost);

Abhi Khanpara (91600103021)


return 0;
}

Output :

Abhi Khanpara (91600103021)


Experiment – 15
Aim : Write a program to display the element of give list.

Program :

#include <stdio.h>

void main()
{
int arr[10];
int i;
printf("\n\nRead and Print elements of an array:\n");
printf("-----------------------------------------\n");

printf("Input 10 elements in the array :\n");


for(i=0; i<10; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}

printf("\nElements in array are: ");


for(i=0; i<10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}

Abhi Khanpara (91600103021)


Output :

Abhi Khanpara (91600103021)


Experiment : 16
Aim : Write a program for the family tree.
Program :
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Family *get_person(void);
char related(struct Family *pmember1, struct Family *pmember2);
char set_ancestry(struct Family *pmember1, struct Family *pmember2);

struct Date
{
int day;
int month;
int year;
};

struct Family
{
struct Date dob;
char name[20];
char father[20];
char mother[20];
struct Family *next;

struct Family *p_to_pa;


struct Family *p_to_ma;
};

int main()
{
struct Family *first = NULL;
struct Family *current = NULL;
struct Family *last = NULL;

char more = '\0';

for( ; ; )
{
printf("\nDo you want to enter details of a%s person (Y or N)? ",
first != NULL?"nother " : "" );
scanf(" %c", &more);
if(tolower(more) == 'n')
break;

Abhi Khanpara (91600103021)


current = get_person();

if(first == NULL)
{
first = current;
last = current;
}
else
{
last->next = current;
current->previous = last;
last = current;
}
}

current = first;

while(current->next != NULL)
{
int parents = 0;
last = current->next;

while(last != NULL)
{
if(related(current, last))
if(++parents == 2)
break;

last = last->next;
}
current = current->next;
}

current = first;

while (current != NULL)


{
printf("\n%s was born %d/%d/%d, and has %s and %s as parents.",
current->name, current->dob.day, current->dob.month,
current->dob. year, current->father, current->mother);
if(current->p_to_pa != NULL )
printf("\n\t%s's birth date is %d/%d/%d ",
current->father, current->p_to_pa->dob.day,
current->p_to_pa->dob.month,
current->p_to_pa->dob.year);
if(current->p_to_ma != NULL)
printf("and %s's birth date is %d/%d/%d.\n ",
current->mother, current->p_to_ma->dob.day,
current->p_to_ma->dob.month,
current->p_to_ma->dob.year);

current = current->next;
}
Abhi Khanpara (91600103021)
current = first;
while(current->next != NULL)
{
last = current;
current = current->next;
free(last);
}
}

struct Family *get_person(void)


{
struct Family *temp;
temp = (struct Family*) malloc(sizeof(struct Family));

printf("\nEnter the name of the person: ");


scanf("%s", temp -> name );

printf("\nEnter %s's date of birth (day month year); ", temp->name);


scanf("%d %d %d", &temp->dob.day, &temp->dob.month, &temp->dob.year);

printf("\nWho is %s's father? ", temp->name );


scanf("%s", temp->father );

printf("\nWho is %s's mother? ", temp -> name );


scanf("%s", temp -> mother );

temp->next = temp->previous = NULL;

temp->p_to_pa = temp->p_to_ma = NULL;


return temp;
}

char set_ancestry(struct Family *pmember1, struct Family *pmember2)


{
if(strcmp(pmember1->father, pmember2->name) == 0)
{
pmember1->p_to_pa = pmember2;
return 1;
}

if( strcmp(pmember1->mother, pmember2->name) == 0)


{
pmember1->p_to_ma = pmember2;
return 1;
}
else
return 0;
}

char related (struct Family *pmember1, struct Family *pmember2)


{
return set_ancestry(pmember1, pmember2) ||
set_ancestry(pmember2, pmember1);
Abhi Khanpara (91600103021)
}

Output :

Abhi Khanpara (91600103021)


Experiment : 17
Aim: Write a program to check given element is in the list or not.

Program:
test_list = [ 1, 6, 3, 5, 3, 4 ]
print("Checking if 4 exists in list ( using loop ) : ")
for i in test_list:
if(i == 4) :
print ("Element Exists")

Output :

Abhi Khanpara (91600103021)


Experiment : 19
Aim: Write a program to print the last element of the list

Program:
test_list = [1, 4, 5, 6, 3, 5]
print ("The original list is : " + str(test_list))
for i in range(0, len(test_list)):
if i == (len(test_list)-1):
print ("The last element of list using loop : "
+ str(test_list[i]))

Output :

Abhi Khanpara (91600103021)


Experiment : 20
Aim: Write a program to print the sum of the elements of the given list

Program:
total = 0
list1 = [11, 5, 17, 18, 23]
for ele in range(0, len(list1)):
total = total + list1[ele]
print("Sum of all elements in given list: ", total)

Output :

Abhi Khanpara (91600103021)


Experiment : 22
Aim : Write a programme for File.
Program:
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;
fptr = fopen("program.txt", "w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}
Output:

Abhi Khanpara (91600103021)

Anda mungkin juga menyukai