0% found this document useful (0 votes)
9 views47 pages

Ai Sahil1

Uploaded by

prashant rajai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views47 pages

Ai Sahil1

Uploaded by

prashant rajai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Artificial Intelligence - 2112901070

3170716 95

Artificial
Intelligenc
e
(3170716)

Lab Manual

Gyanmanjari Institute Of Technology 1


Artificial Intelligence - 2112901070
3170716 95

1. Write a program to implement Tic-Tac-Toe game

problem #include <stdbool.h>


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define COMPUTER 1
#define HUMAN 2
#define SIDE 3
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'

//-----------------Intelligent Moves start

struct Move {
int row, col;
};

char player = 'x', opponent = 'o';

// This function returns true if there are moves


// remaining on the board. It returns false if
// there are no moves left to play.
bool isMovesLeft(char board[3]
[3])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (board[i][j] == '_')
return true;
return false;
}

// This is the evaluation


function int evaluate(char b[3]
[3])
{
// Checking for Rows for X or O victory.
for (int row = 0; row < 3; row++) {
if (b[row][0] == b[row][1]
&& b[row][1] == b[row][2])
{ if (b[row][0] == player)
return +10;
else if (b[row][0] == opponent)
return -10}
}
Gyanmanjari Institute Of Technology 2
Artificial Intelligence - 2112901070
3170716 95

// Checking for Columns for X or O victory.


for (int col = 0; col < 3; col++) {

Gyanmanjari Institute Of Technology 3


Artificial Intelligence - 2112901070
3170716 95

if (b[0][col] == b[1][col]
&& b[1][col] == b[2][col]) {
if (b[0][col] == player)
return +10;

else if (b[0][col] == opponent)


return -10;
}
}

// Checking for Diagonals for X or O victory.


if (b[0][0] == b[1][1] && b[1][1] == b[2][2])
{
if (b[0][0] == player)
return +10;
else if (b[0][0] == opponent)
return -10;
}

if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) {


if (b[0][2] == player)
return +10;
else if (b[0][2] == opponent)
return -10;
}

// Else if none of them have won then return 0


return 0;
}

// This is the minimax function. It considers all //


the possible ways the game can go and returns //
the value of the board
int minimax(char board[3][3], int depth, bool isMax)
{
int score = evaluate(board);

// If Maximizer has won the game return his/her


// evaluated score
if (score == 10)

Gyanmanjari Institute Of Technology 4


Artificial Intelligence - 2112901070
3170716 95

return score;

// If Minimizer has won the game return his/her


// evaluated score
if (score == -10)
return score;

// If there are no more moves and no winner then


// it is a tie
if (isMovesLeft(board) == false)
return 0;

// If this maximizer's move


if (isMax) {
int best = -1000;

// Traverse all cells


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// Check if cell is
empty if (board[i][j] ==
'_') {
// Make the move
board[i][j] = player;
int val
= minimax(board, depth + 1, !isMax);
if (val > best) {
best = val;
}

// Undo the move


board[i][j] = '_';
}
}
}
return best;
}

// If this minimizer's move


else {
int best = 1000;

// Traverse all cells


for (int i = 0; i < 3; i++) {

Gyanmanjari Institute Of Technology 5


Artificial Intelligence - 2112901070
3170716 95

for (int j = 0; j < 3; j++) {


// Check if cell is
empty if (board[i][j] ==
'_') {
// Make the move
board[i][j] = opponent;
// Call minimax recursively and choose
int val
= minimax(board, depth + 1, !isMax);
if (val < best) {
best = val;
}
// Undo the move
board[i][j] = '_';
}
}
}
return best;
}
}

// This will return the best possible move for the player
struct Move findBestMove(char board[3][3])
{
int bestVal = -1000;
struct Move bestMove;
bestMove.row = -1;
bestMove.col = -1;

// Traverse all cells, evaluate minimax function for


// all empty cells. And return the cell with optimal
// value.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// Check if cell is empty
if (board[i][j] == '_') {
// Make the move
board[i][j] = player;

// compute evaluation function for this


// move.
int moveVal = minimax(board, 0, false);

// Undo the move

Gyanmanjari Institute Of Technology 6


Artificial Intelligence - 2112901070
3170716 95

board[i][j] = '_';

// If the value of the current move is


// more than the best value, then update
// best/
if (moveVal > bestVal) {
bestMove.row = i;
bestMove.col = j;
bestVal =
moveVal;
}
}
}
}

// printf("The value of the best Move is : %d\n\n",


// bestVal);

return bestMove;
}

// Intelligent Moves end

// Function to display the game board


void showBoard(char board[][SIDE])
{
printf("\n\n");
printf("\t\t\t %c | %c | %c \n", board[0][0], board[0]
[1], board[0][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n", board[1][0], board[1]
[1], board[1][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);
}

// Function to show the instructions


void showInstructions()
{
printf("\t\t\t Tic-Tac-Toe\n\n");
printf("Choose a cell numbered from 1 to 9 as below
" "and play\n\n");

Gyanmanjari Institute Of Technology 7


Artificial Intelligence - 2112901070
3170716 95

printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");

printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");
}
// Function to initialise the game
void initialise(char board[][SIDE], int moves[])
{
srand(time(NULL));

// Initially, the board is empty


for (int i = 0; i < SIDE; i++) {
for (int j = 0; j < SIDE; j++)
board[i][j] = ' ';
}

// Fill the moves with numbers


for (int i = 0; i < SIDE * SIDE; i++)
moves[i] = i;

// Randomize the moves


for (int i = 0; i < SIDE * SIDE; i++) {
int randIndex = rand() % (SIDE * SIDE);
int temp = moves[i];
moves[i] =
moves[randIndex];
moves[randIndex] = temp;
}
}

// Function to declare the winner of the game


void declareWinner(int whoseTurn)
{
if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n");
}

// Function to check if any row is crossed with the same

Gyanmanjari Institute Of Technology 8


Artificial Intelligence - 2112901070
3170716 95

// player's move
int rowCrossed(char board[][SIDE])
{
for (int i = 0; i < SIDE; i++) {
if (board[i][0] == board[i][1]
&& board[i][1] == board[i][2]
&& board[i][0] != ' ')
return 1;
}
return 0;
}

// Function to check if any column is crossed with the same


// player's move
int columnCrossed(char board[][SIDE])
{
for (int i = 0; i < SIDE; i++) {
if (board[0][i] == board[1][i]
&& board[1][i] == board[2][i]
&& board[0][i] != ' ')
return 1;
}
return 0;
}

// Function to check if any diagonal is crossed with the


// same player's move
int diagonalCrossed(char board[][SIDE])
{
if ((board[0][0] == board[1][1]
&& board[1][1] == board[2][2]
&& board[0][0] != ' ')
|| (board[0][2] == board[1][1]
&& board[1][1] == board[2][0]
&& board[0][2] != ' '))
return 1;

return 0;
}

// Function to check if the game is over


int gameOver(char board[][SIDE])
{

Gyanmanjari Institute Of Technology 9


Artificial Intelligence - 2112901070
3170716 95

return (rowCrossed(board) || columnCrossed(board)


|| diagonalCrossed(board));
}

// Function to play Tic-Tac-Toe


void playTicTacToe(int whoseTurn)
{
// A 3*3 Tic-Tac-Toe board for playing
char board[SIDE][SIDE];
int moves[SIDE * SIDE];

// Initialise the game


initialise(board,
moves);

// Show the instructions before playing


showInstructions();

int moveIndex = 0, x, y;

// Keep playing until the game is over or it is a draw


while (!gameOver(board) && moveIndex != SIDE * SIDE)
{ if (whoseTurn == COMPUTER) {

char tempBoard[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++) {
if (board[i][j] == 'X') {
tempBoard[i][j] = 'x';
}
else if (board[i][j] == 'O') {
tempBoard[i][j] = 'o';
}
else
{ tempBoard[i][j] = '_';

}
}
}
struct Move thisMove = findBestMove(tempBoard);
x = thisMove.row;
y = thisMove.col;

board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d %d\n",

Gyanmanjari Institute Of Technology 10


Artificial Intelligence - 2112901070
3170716 95

COMPUTERMOVE, x, y);
showBoard(board);
moveIndex++;
whoseTurn =
HUMAN;
}
else if (whoseTurn == HUMAN)
{ int move;
printf("Enter your move (1-9): ");
scanf("%d", &move);
if (move < 1 || move > 9) {
printf("Invalid input! Please enter a "
"number between 1 and 9.\n");
continue;
}
x = (move - 1) / SIDE;
y = (move - 1) %
SIDE; if (board[x][y]
== ' ') {
board[x][y] = HUMANMOVE;
showBoard(board);
moveIndex++;
if (gameOver(board)) {
declareWinner(HUMAN);
return;
}
whoseTurn = COMPUTER;
}
else
{ printf("Cell %d is already occupied. Try " "again.\
n",
move);

}
}
}

// If the game has drawn


if (!gameOver(board) && moveIndex == SIDE * SIDE)
printf("It's a draw\n");
else {
// Toggling the user to declare the actual winner
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;

Gyanmanjari Institute Of Technology 11


Artificial Intelligence - 2112901070
3170716 95

// Declare the winner


declareWinner(whoseTurn);
}
}

// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);

return 0;
}
1) Write a program to implement BFS (for 8 puzzle problem or Water Jug problem or any
AI search problem)

#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);
}
temp = left;
while(1)
{
if((temp->x == next->x) && (temp->y == next->y)){
return(1);
}

Gyanmanjari Institute Of Technology 12


Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 13


Artificial Intelligence - 2112901070
3170716 95

tempRight->next = genNewState(tempRight, jug1, jug2, f1, f2);


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

Gyanmanjari Institute Of Technology 14


Artificial Intelligence - 2112901070
3170716 95

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

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;
}
temp1 = temp1->next;
printf("(%d , %d)\n", temp2->x, temp2-
>y); if((temp2->x == f1)&&(temp2->y ==
f2)){ break;
}
temp2 = temp2->next;
}
}
void main()
{

Gyanmanjari Institute Of Technology 15


Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 16


Artificial Intelligence - 2112901070
3170716 95

2) Write a program to implement DFS (for 8 puzzle problem or Water Jug problem or any
AI search problem)

#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 :
"); 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);
}

Gyanmanjari Institute Of Technology 17


Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 18


Artificial Intelligence - 2112901070
3170716 95

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 {
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);
Gyanmanjari Institute Of Technology 19
Artificial Intelligence - 2112901070
3170716 95

Gyanmanjari Institute Of Technology 20


Artificial Intelligence - 2112901070
3170716 95

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))
{
tempRight->next = genNewState(tempRight, jug1, jug2, f1, f2);
tempRight = tempRight->next;
tempRight->next =
NULL; flag2 = 1;
}
if((flag1 == 0) && (flag2 == 0))
break;
}
}

Gyanmanjari Institute Of Technology 21


Artificial Intelligence - 2112901070
3170716 95

3) Write a program to implement Single Player Game (Using any Heuristic Function)

#include <stdio.h>
#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;
printf("This is the game of Tic Tac Toe.\n");
printf("You will be playing against the computer.\
n"); done = ' ';
init_matrix();
do {
disp_matrix();
get_player_move();
done = check(); /* see if winner
*/ if (done != ' ') break; /* winner!
*/ get_computer_move();
done = check(); /* see if winner */
} while (done == ' ');
if (done == 'X') printf("You won!\n");
else printf("I won!!!!\n");
disp_matrix(); /* show final positions */
return 0;
}
/* Initialize the matrix.
*/ void init_matrix(void)
{ int i, j;

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


for (j = 0; j < 3; j++) matrix[i][j] = ' ';
}
/* Get a player's move. */
void get_player_move(void)
{ int x, y;

printf("Enter X,Y coordinates for your move: "); scanf("%d


%*c%d", & x, & y);
x--;
y--;

Gyanmanjari Institute Of Technology 22


Artificial Intelligence - 2112901070
3170716 95

if (matrix[x][y] != ' ') {

printf("Invalid move, try again.\n");


get_player_move();
} else matrix[x][y] = 'X';
}
/* Get a move from the computer. */
void get_computer_move(void) {
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) {
printf("draw\n");
exit(0);
} else matrix[i]
[j] = 'O';
}

/* Display the matrix on the screen.


*/ void disp_matrix(void) {
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");
}

/* See if there is a winner. */


char check(void) {
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] &&
Gyanmanjari Institute Of Technology 23
Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 24


Artificial Intelligence - 2112901070
3170716 95

4) Write a program to Implement A*

Algorithm. #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);
}
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;

Gyanmanjari Institute Of Technology 25


Artificial Intelligence - 2112901070
3170716 95

Gyanmanjari Institute Of Technology 26


Artificial Intelligence - 2112901070
3170716 95

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;
}
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;
cellDetails[i][j].parent_j = j;

Gyanmanjari Institute Of Technology 27


Artificial Intelligence - 2112901070
3170716 95

set < pPair > openList;


openList.insert(make_pair(0.0, make_pair(i, j)));

Gyanmanjari Institute Of Technology 28


Artificial Intelligence - 2112901070
3170716 95

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;
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;
Gyanmanjari Institute Of Technology 29
Artificial Intelligence - 2112901070
3170716 95

return;

Gyanmanjari Institute Of Technology 30


Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 31


Artificial Intelligence - 2112901070
3170716 95

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


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)
{ 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,

Gyanmanjari Institute Of Technology 32


Artificial Intelligence - 2112901070
3170716 95

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;
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;
} else if (closedList[i + 1][j + 1] == false &&
isUnBlocked(grid, i + 1, j + 1) == true) {
Gyanmanjari Institute Of Technology 33
Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 34


Artificial Intelligence - 2112901070
3170716 95

int main() {
/* Description of the Grid1--> 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 },
{ 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);
}
5) Write a program to implement mini-max algorithm for any game

development #include <stdio.h>

char gridChar(int i)
{ switch(i) {
case -1:
return 'X';
case 0:
return '
'; case 1:
return 'O';
}
}

void draw(int b[9]) {


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 win(const int board[9]) {
//determines if a player has won, returns 0 otherwise.

Gyanmanjari Institute Of Technology 35


Artificial Intelligence - 2112901070
3170716 95

unsigned wins[8][3] = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};


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

int minimax(int board[9], int player) {


//How is the position like for player (their turn) on board?
int winner = win(board);
if(winner != 0) return winner*player;

move = -1;
int score = -2;//Losing moves are preferred to no move
int i;
for(i = 0; i < 9; ++i) {//For all moves,
if(board[i] == 0) {//If legal,
board[i] = player;//Try the move
int thisScore = -minimax(board, player*-1);
if(thisScore > score) {
score =
thisScore; move
= i;
}//Pick the one that's worst for the opponent
board[i] = 0;//Reset board after try
}
}
if(move == -1) return 0;
return score;
}

void computerMove(int board[9])


{ int move = -1;
int score = -2;
int i;
for(i = 0; i < 9; ++i)
{ if(board[i] == 0)
{ board[i] = 1;
int tempScore = -minimax(board, -1);
board[i] = 0;

Gyanmanjari Institute Of Technology 36


Artificial Intelligence - 2112901070
3170716 95

if(tempScore > score)


{ score = tempScore;
move = i;
}
}
}
//returns a score based on minimax tree at a given node.
board[move] = 1;
}

void playerMove(int board[9])


{ int move = 0;
do {
printf("\nInput move ([0..8]): ");
scanf("%d", &move);
printf("\n");
} while (move >= 9 || move < 0 && board[move] == 0);
board[move] = -1;
}

int main() {
int board[9] = {0,0,0,0,0,0,0,0,0};
//computer squares are 1, player squares are -1.
printf("Computer: O, You: X\nPlay (1)st or (2)nd? ");
int player=0;
scanf("%d",&player);
printf("\n");
unsigned turn;
for(turn = 0; turn < 9 && win(board) == 0; ++turn)
{ if((turn+player) % 2 == 0)
computerMove(board);
else {
draw(board);
playerMove(board);
}
}
switch(win(board))
{ case 0:
printf("A draw. How droll.\n");
break;
case 1:
draw(board);
printf("You lose.\n");

Gyanmanjari Institute Of Technology 37


Artificial Intelligence - 2112901070
3170716 95

break;
case -1:
printf("You win. Inconceivable!\
n"); break;
}
}

Gyanmanjari Institute Of Technology 38


Artificial Intelligence - 2112901070
3170716 95

6) Write a program to solve Tower of Hanoi problem using

Prolog. move(1,X,Y,_) :-
write('Move top disk from '), write(X), write(' to '), write(Y), nl.
move(N,X,Y,Z) :-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).

Gyanmanjari Institute Of Technology 39


Artificial Intelligence - 2112901070
3170716 95

7) Write a program to solve N-Queens problem using

Prolog. #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;
/* 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 },
{ 0, 0, 0, 0 }

Gyanmanjari Institute Of Technology 40


Artificial Intelligence - 2112901070
3170716 95

};

Gyanmanjari Institute Of Technology 41


Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 42


Artificial Intelligence - 2112901070
3170716 95

8) Write a program to solve 8 puzzle problem using

Prolog. #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)
{ 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);
}

Gyanmanjari Institute Of Technology 43


Artificial Intelligence - 2112901070
3170716 95

void printPath(Node * root)


{ if (root == NULL)
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;
}
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}
};

Gyanmanjari Institute Of Technology 44


Artificial Intelligence - 2112901070
3170716 95

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;

Gyanmanjari Institute Of Technology 45


Artificial Intelligence - 2112901070
3170716 95

9) Write a program to solve travelling salesman problem using

Prolog. #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;
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) {

Gyanmanjari Institute Of Technology 46


Artificial Intelligence - 2112901070
3170716 95

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

Gyanmanjari Institute Of Technology 47

You might also like