Ai Pract 2024
Ai Pract 2024
College of
Engineering
Opp. Gujarat University, Navrangpura, Ahmedabad -
380015
LAB MANUAL
Branch: Computer Engineering
Artificial Intelligence
(3170716)
Semester: VII
Faculty Details:
1. Prof. Dr. V. B. Vaghela
2. Prof. H. D. Rajput
Artificial Intelligence (3170716)
CERTIFICATE
Practical Rubrics
SIGN OF FACULTY
Artificial Intelligence (3170716)
Pract.
RB1 (2) RB2 (3) RB3 (3) RB4 (2) Total (10) Date Faculty Sign
No.
PART – A AI Programs
1
2
3
4
5
6
PART – B Prolog Programs
1
2
3
4
5
6
7
8
9
10
11
12
Artificial Intelligence (3170716)
Practical - 1
Aim: Write a program to implement Tic-Tac-Toe game problem.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#define COMPUTER 1
#define HUMAN 2
#define SIDE 3 // Length of the board
// Function to check if any row is crossed with the same player's move
bool 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 true;
}
return false;
}
// Function to check if any column is crossed with the same player's move
bool 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 true;
}
return false;
}
// Function to check if any diagonal is crossed with the same player's move
bool diagonalCrossed(char board[][SIDE]) {
if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] != ' ')
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)
return true;
if (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] != ' ')
return true;
return false;
}
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;
declareWinner(whoseTurn);
}
}
// Driver program
int main() {
playTicTacToe(COMPUTER);
return 0;
}
Output:
Tic-Tac-Toe
1 | 2 | 3
--------------
4 | 5 | 6
--------------
7 | 8 | 9
- - - - - - - - - -
| |
--------------
| | O
--------------
| |
| |
--------------
| | O
--------------
X | |
| |
--------------
| O | O
--------------
X | |
X | |
--------------
| O | O
--------------
X | |
X | |
--------------
| O | O
--------------
X | | O
X | |
--------------
| O | O
--------------
X | X | O
X | |
--------------
O | O | O
--------------
X | X | O
Practical – 2
Aim: Write a program to implement BFS (for 8 puzzle problem or Water Jug
problem or any AI search problem).
Given two empty jugs of m and n litres respectively. The jugs don’t have
markings to allow measuring smaller quantities. You have to use the jugs to
measure d litres of water. The task is to find the minimum number of operations to
be performed to obtain d litres of water in one of the jugs. In case of no solution
exist, return -1.
The operations you can perform are:
Empty a Jug
Fill a Jug
Pour water from one jug to the other until one of the jugs is either empty or
full.
Example:
Input: m = 3, n = 5, d = 4
Output: 6
Explanation: Operations are as follow:
Initially, both jugs are empty (jug1 = 0, jug2 = 0).
Step 1: Fill the 5 liter jug -> (0, 5).
Step 2: Pour from the 5 liter jug to the 3 liter jug -> (3, 2).
Step 3: Empty the 3 liter jug -> (0, 2).
Step 4: Pour the 2 liters from the 5-liter jug to the 3 liter jug -> (2, 0).
Step 5: Fill the 5 liter jug again -> (2, 5).
Step 6: Pour 1 liter from the 5 liter jug into the 3 liter jug -> (3, 4).
Now, the 5 liter jug contains exactly 4 liters, so we stop and return 6 steps.
Input: m = 8, n = 56, d = 46
Output: -1
Explanation: Not possible to fill any one of the jug with 46 litre of water.
#include <bits/stdc++.h>
using namespace std;
queue<vector<int>> q;
while (!q.empty()){
// 1: Fill jug1
if (!visited[m][jug2]){
visited[m][jug2] = true;
q.push({m, jug2, steps + 1});
}
// 2: Fill jug2
if (!visited[jug1][n]){
visited[jug1][n] = true;
q.push({jug1, n, steps + 1});
}
// 3: Empty jug1
if (!visited[0][jug2]){
visited[0][jug2] = true;
q.push({0, jug2, steps + 1});
}
// 4: Empty jug2
if (!visited[jug1][0]){
visited[jug1][0] = true;
q.push({jug1, 0, steps + 1});
}
steps + 1});
}
// If no solution is found
return -1;
}
int main(){
Output
Practical – 3
8 puzzle Problem
Given a 3×3 board with 8 tiles (each numbered from 1 to 8) and one empty space, the objective
is to place the numbers to match the final configuration using the empty space. We can slide
four adjacent tiles (left, right, above, and below) into the empty space.
Approach:
1. Start from the root node.
2. Explore the leftmost child node recursively until you reach a leaf node or a goal
state.
3. If a goal state is reached, return the solution.
4. If a leaf node is reached without finding a solution, backtrack to explore other
branches.
// stores matrix
int mat[N][N];
node->cost = INT_MAX;
return node;
}
printf("\n");
}
// Driver code
int main()
{
// Initial configuration
// Value 0 is used for empty space
int initial[N][N] =
{
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};
solve(initial, x, y, final);
return 0;
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)
}
Output :
1 2 3
5 6 0
7 8 4
1 2 3
5 0 6
7 8 4
1 2 3
5 8 6
7 0 4
1 2 3
5 8 6
0 7 4
Practical-4
Aim: - Write a program to implement Single Player Game (Using any
Heuristic Function)
Code: -
import random
def heuristic_guess(low, high): return (low + high) //
2 def play_game():
print("Welcome to the Guessing Game!") target_number = random.randint(1, 100) low, high
= 1, 100
attempts = 0 while True:
guess = heuristic_guess(low, high) print(f"I guess
{guess}") if guess == target_number:
print(f"Congratulations! I guessed the number {target_number} in {attempts} attempts.")
break
elif guess < target_number: print("Too
low!") low = guess + 1 else:
print("Too high!") high = guess -
1 attempts += 1
if name == " main ": play_game()
OUTPUT :
Practical-5
Aim: Implement A*algorithm.
Code:
import heapq
class Node:
def init (self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state
self.parent = parent
self.action = action
self.cost = cost
self.heuristic = heuristic
def lt (self, other):
return (self.cost + self.heuristic) < (other.cost +
other.heuristic) def astar(start_state, goal_state, get_neighbors,
heuristic):
open_list = []
closed_set = set()
start_node = Node(start_state, None, None, 0, heuristic(start_state, goal_state))
heapq.heappush(open_list, start_node)while open_list:
current_node = heapq.heappop(open_list)
if current_node.state == goal_state:
path = []
while current_node:
path.append((current_node.state, current_node.action))
current_node = current_node.parent
return list(reversed(path))
closed_set.add(current_node.state)
for neighbor_state, action, step_cost in get_neighbors(current_node.state):
if neighbor_state in closed_set:
continue
g_score = current_node.cost + step_cost
h_score = heuristic(neighbor_state, goal_state)
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < len(grid) and 0 <= new_y < len(grid[0]) and grid[new_x][new_y] ==
0:
neighbors.append(((new_x, new_y), f"Move to ({new_x}, {new_y})", 1))
return neighbors
def manhattan_distance(state, goal):
x1, y1 = state
x2, y2 = goal
return abs(x1 - x2) + abs(y1 - y2)
path = astar(start, goal, get_neighbors, manhattan_distance)
if path:
for state, action in path:
print(f"Action: {action}, State: {state}")
else:
print("No path found.")
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)
Output:
Practical-6
Aim: Write a program to implement mini-max algorithm for any game
development.
Code:
# A simple Python3 program to find # maximum score
that # maximizing player can get import math
def minimax (curDepth, nodeIndex,
maxTurn, scores, targetDepth):
# base case : targetDepth reached if (curDepth ==
targetDepth): return scores[nodeIndex]
if (maxTurn):
return max(minimax(curDepth + 1, nodeIndex * 2,
False, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1, False, scores,
targetDepth))
else:
return min(minimax(curDepth + 1, nodeIndex * 2,
True, scores, targetDepth), minimax(curDepth + 1, nodeIndex * 2 + 1, True, scores,
targetDepth))
# Driver code
scores = [3, 5, 2, 9, 12, 5, 23, 23]
treeDepth = math.log(len(scores), 2)
print("The optimal value is : ", end = "") print(minimax(0, 0, True, scores, treeDepth))
# This code is contributed # by rootshadow
Output:
Practical-7
Aim: Assume given a set of facts of the form father (name1, name2)
(name1 is the father of name2).
Code:
female(pam).
female(liz).
female(pat).
female(ann).
male(jim).
male(bob).
male(tom).
male(peter).
parent(pam,bob).
parent(tom,bob).
parent(tom,liz).
parent(bob,ann).
parent(bob,pat).
parent(pat,jim).
parent(bob,peter).
parent(peter,jim).
mother(X,Y):- parent(X,Y),female(X).
father(X,Y):-parent(X,Y),male(X).
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
grandparent(X,Y):-parent(X,Z),parent(Z,Y).
grandmother(X,Z):-mother(X,Y),parent(Y,Z).
grandfather(X,Z):-father(X,Y),parent(Y,Z).
wife(X,Y):-parent(X,Z),parent(Y,Z),female(X),male(Y). uncle(X,Z):-
brother(X,Y),parent(Y,Z).
Output:
Practical-8
Aim: Define a predicate brother(X,Y) which holds iff X and Y are
brothers. Define a predicate cousin(X,Y) which holds iff X and Y are
cousins.Define a predicate grandson(X,Y) which holds iff X is a grandson
of Y. Define a predicate descendent(X,Y) which holds iff X is a
descendent of Y.
Consider the following genealogical tree: father(a,b).
father(a,c). father(b,d). father(b,e). father(c,f).
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).
Code:
father(kevin,milu). father(kevin,yash). father(milu,meet). father(milu,raj). father(yash,jay).
brother(X,Y):-father(K,X),father(K,Y).
cousin(A,B):-father(K,X),father(K,Y),father(X,A),father(Y,B). grandson(X,Y):-
father(X,K),father(K,Y).
descendent(X,Y):-father(K,X),father(K,Y).
descendent(X,Y):-father(K,X),father(K,Y),father(X,A),father(Y,B).
Output:
Practical-9
Aim: Write a program to solve Tower of Hanoi problem using Prolog.
Code:
% Base case: moving a single disk
move(1,X,Y,_) :-
write('Move top disk from '),
write(X),
write(' to '),
write(Y),
nl.
% Recursive case: moving N disks
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).
Output:
Practical-10
Aim: Write a program to solve N-Queens problem using Prolog. Code:
% Define the goal state goal([1, 2, 3, 4, 5, 6, 7, 8,
0]).
% Define the possible moves
move([X1, 0, X3, X4, X5, X6, X7, X8, X9], [0, X1, X3, X4, X5, X6, X7, X8, X9]).
move([X1, X2, 0, X4, X5, X6, X7, X8, X9], [X2, 0, X1, X4, X5, X6, X7, X8, X9]).
% ... (define other moves here) ...
% Define the solve predicate solve(Puzzle) :-
depth_first_search(Puzzle,[Puzzle],Moves), display_moves(Moves).
% Define the depth-first search predicate depth_first_search(Puzzle,_Visited,
[Puzzle]) :- goal(Puzzle). depth_first_search(Puzzle,Hist,[Puzzle|Moves]) :-
move(Puzzle,Puzzle1),
not(member(Puzzle1,Hist)),depth_first_search(Puzzle1,
[Puzzle1|Hist],Moves).
Output:
Practical-11
Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)
Output:
Practical-12
Aim: Write a program to solve travelling salesman problem using Prolog. Code:
% Define the distances between cities distance(city1,
city2, 10).
Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)
Output: