0% found this document useful (0 votes)
12 views34 pages

Ai Pract 2024

Uploaded by

patelhasti2654
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)
12 views34 pages

Ai Pract 2024

Uploaded by

patelhasti2654
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/ 34

L. D.

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

This is to certify that Mr./Ms. MODI PRIYA DINESHKUMAR Enrollment Number


220283107014 has satisfactorily completed the practical work in “Artificial
Intelligence” subject at L D College of Engineering, Ahmedabad-380015.

Date of Submission: _______________

Sign of Faculty: _______________

Head of Department: _______________


Artificial Intelligence (3170716)

L. D. College of Engineering, Ahmedabad


Department of Computer Engineering
Practical List

Subject Name: Artificial Intelligence (3170716)


Term: 2024-2025
Sr. Page CO Marks
Title Date Sign
No. No. (10)
PART-A AI Programs
1 Write a program to implement Tic-Tac-Toe game CO3
problem.
2 Write a program to implement BFS (for 8 puzzle CO1
problem or Water Jug problem or any AI search
problem).
3 Write a program to implement DFS (for 8 puzzle CO1
problem or Water Jug problem or any AI search
problem).
4 Write a program to implement Single Player Game CO3
(Using any Heuristic Function).
5 Write a program to Implement A* Algorithm. CO4
6 Write a program to implement mini-max algorithm for any CO4
game development.
PART – B Prolog Programs
1 Write a PROLOG program to represent Facts. Make CO2
some queries based on the facts.
2 Write a PROLOG program to represent Rules. Make some CO2
queries based on the facts and rules
3 Write a PROLOG program to define the relations using the CO5
given predicates.
4 Write a PROLOG program to perform addition, CO5
subtraction, multiplication and division of two numbers
using arithmetic operators.
5 Write a PROLOG program to display the numbers CO5
from 1 to 10 by simulating the loop using recursion.
6 Write a PROLOG program to count number of CO5
elements in a list.
7 Write a PROLOG program to perform various operations CO5
on a list.
8 Write a PROLOG program to reverse the list. CO5
9 Write a PROLOG program to demonstrate the use of CO5
CUT and FAIL predicate.
10 Write a PROLOG program to solve the Tower of CO5
Hanoi problem.
11 Write a PROLOG program to solve the N-Queens CO5
problem.
Artificial Intelligence (3170716)

12 Write a PROLOG program to solve the Travelling Salesman CO5


problem

L. D. College of Engineering, Ahmedabad


Department of Computer Engineering

Practical Rubrics

Subject Name: Artificial Intelligence Subject Code: (3170716)


Term: 2024-2025
Rubrics Criteria Marks Excellent (3) Good (2) Satisfactory (1) Need
ID Improvement (0)
Moderate (40-
RB1 Regularity 02 -- High (>70%) Poor (0-40%)
70%)
Appropriate &
Limited Very Less
Full Not able to
Problem Identification of Identification of
Identification of analyze the
Analysis and the Problem / the Problem /
RB2 03 the Problem & problem and
Development Incomplete Very Less
Complete develop the
of Solution Solution for the Solution for the
Solution for the solution
Problem Problem
Problem
Concept Concept is very Concept is clear Just overview
Concept is not
RB3 Clarity and 03 clear with proper at moderate of the concept is
clear.
Understanding understanding level. known.
Proper
Documentatio
Not up to format not
RB4 Documentation 02 -- n completed
standard. followed,
neatly.
incomplete.

SIGN OF FACULTY
Artificial Intelligence (3170716)

L. D. College of Engineering, Ahmedabad


Department of Computer Engineering
LABORATORY PRACTICALS ASSESSMENT
Subject Name: Artificial Intelligence (3170716)
Term: ODD 2024-25
Enroll. No.:
Name:

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>

using namespace std;

#define COMPUTER 1
#define HUMAN 2
#define SIDE 3 // Length of the board

// Computer will move with 'O' and human with 'X'


#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'

// Function to show the current board status


void showBoard(char board[][SIDE]) {
cout << endl << "\t\t\t " << board[0][0] << " | " << board[0][1] << " | " << board[0]
[2] << endl;
cout << "\t\t\t--------------" << endl;
cout << "\t\t\t " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] <<
endl;
cout << "\t\t\t--------------" << endl;
cout << "\t\t\t " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] <<
endl << endl;
}

// Function to show the instructions


void showInstructions() {
cout << "\t\t\t Tic-Tac-Toe" << endl << endl;
cout << "Choose a cell numbered from 1 to 9 as below and play" << endl << endl;
cout << "\t\t\t 1 | 2 | 3" << endl;
cout << "\t\t\t--------------" << endl;
cout << "\t\t\t 4 | 5 | 6" << endl;
cout << "\t\t\t--------------" << endl;
cout << "\t\t\t 7 | 8 | 9" << endl << endl;
cout << "-\t-\t-\t-\t-\t-\t-\t-\t-\t-" << endl << endl;
}
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

// Function to initialise the game


void initialise(char board[][SIDE], int moves[]) {
srand(time(NULL));
for (int i = 0; i < SIDE; i++) {
for (int j = 0; j < SIDE; j++)
board[i][j] = ' ';
}
for (int i = 0; i < SIDE * SIDE; i++)
moves[i] = i;
random_shuffle(moves, moves + SIDE * SIDE);
}

// Function to declare the winner of the game


void declareWinner(int whoseTurn) {
if (whoseTurn == COMPUTER)
cout << "COMPUTER has won" << endl;
else
cout << "HUMAN has won" << endl;
}

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

// Function to check if the game is over


bool gameOver(char board[][SIDE]) {
return (rowCrossed(board) || columnCrossed(board) || diagonalCrossed(board));
}

// Function to play Tic-Tac-Toe


void playTicTacToe(int whoseTurn) {
char board[SIDE][SIDE];
int moves[SIDE * SIDE];
initialise(board, moves);
showInstructions();
int moveIndex = 0, x, y;
while (gameOver(board) == false && moveIndex != SIDE * SIDE) {
if (whoseTurn == COMPUTER) {
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
cout << "COMPUTER has put a " << COMPUTERMOVE << " in cell " <<
moves[moveIndex] + 1 << endl;
showBoard(board);
moveIndex++;
whoseTurn = HUMAN;
} else if (whoseTurn == HUMAN) {
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
cout << "HUMAN has put a " << HUMANMOVE << " in cell " <<
moves[moveIndex] + 1 << endl;
showBoard(board);
moveIndex++;
whoseTurn = COMPUTER;
}
}
if (gameOver(board) == false && moveIndex == SIDE * SIDE)
cout << "It's a draw" << endl;
else {
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

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

Choose a cell numbered from 1 to 9 as below and


play

1 | 2 | 3
--------------
4 | 5 | 6
--------------
7 | 8 | 9

- - - - - - - - - -

COMPUTER has put a O in cell 6

| |
--------------
| | O
--------------
| |

HUMAN has put a X in cell 7

| |
--------------
| | O
--------------
X | |

COMPUTER has put a O in cell 5

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

| |
--------------
| O | O
--------------
X | |

HUMAN has put a X in cell 1

X | |
--------------
| O | O
--------------
X | |

COMPUTER has put a O in cell 9

X | |
--------------
| O | O
--------------
X | | O

HUMAN has put a X in cell 8

X | |
--------------
| O | O
--------------
X | X | O

COMPUTER has put a O in cell 4

X | |
--------------
O | O | O
--------------
X | X | O

COMPUTER has won

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

Practical – 2

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

Water Jug problem using BFS




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;

// Function to find the minimum operations to obtain d litres


// in one jug
int minSteps(int m, int n, int d)
{
// Check if the target is achievable
if (d > max(m, n)) return -1;

// Queue for BFS: each state is (jug1, jug2, steps)


Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

queue<vector<int>> q;

// For tracking the visited states


vector<vector<bool>> visited(m + 1,
vector<bool>(n + 1, false));

// Start with both jugs empty


q.push({0, 0, 0}); // (jug1, jug2, steps)
visited[0][0] = true;

while (!q.empty()){

auto curr = q.front();


q.pop();

int jug1 = curr[0];


int jug2 = curr[1];
int steps = curr[2];

// If we have found the solution


if (jug1 == d || jug2 == d) return steps;

// All Possible operations are:

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

// 5: Pour jug1 into jug2


int pour1to2 = min(jug1, n - jug2);
if (!visited[jug1 - pour1to2][jug2 + pour1to2]){
visited[jug1 - pour1to2][jug2 + pour1to2] = true;
q.push({jug1 - pour1to2, jug2L.+D.pour1to2,
Computer Engineering Department College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

steps + 1});
}

// 6: Pour jug2 into jug1


int pour2to1 = min(jug2, m - jug1);
if (!visited[jug1 + pour2to1][jug2 - pour2to1]){
visited[jug1 + pour2to1][jug2 - pour2to1] = true;
q.push({jug1 + pour2to1, jug2 - pour2to1,
steps + 1});
}
}

// If no solution is found
return -1;
}

int main(){

// jug1 = 4 litre, jug2 = 3 litre


int m = 4, n = 3, d = 2;
cout << minSteps(m, n, d);
return 0;
}

Output

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

Practical – 3

Aim: Write a program to implement DFS (for 8 puzzle problem or Water


Jug problem or any AI search problem).

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.

1. 8 puzzle Problem using DFS (Brute-Force)


We can perform a depth-first search on state-space (Set of all configurations of a
given problem i.e. all states that can be reached from the initial state) tree.
 Depth-first search on state-space tree.
 Successive moves may take us away from the goal.
 Inefficient as it explores all paths equally.

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.

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

// Program to print path from root node to destination node


// for N*N -1 puzzle algorithm using Branch and Bound
// The solution assumes that instance of puzzle is solvable
#include <bits/stdc++.h>
using namespace std;
#define N 3

// state space tree nodes


struct Node
{
// stores the parent node of the current node
// helps in tracing path when the answer is found
Node* parent;

// stores matrix
int mat[N][N];

// stores blank tile coordinates


int x, y;
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

// stores the number of misplaced tiles


int cost;

// stores the number of moves so far


int level;
};

// Function to print N x N matrix


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

// Function to allocate a new node


Node* newNode(int mat[N][N], int x, int y, int newX,
int newY, int level, Node* parent)
{
Node* node = new Node;

// set pointer for path to root


node->parent = parent;

// copy data from parent node to current node


memcpy(node->mat, mat, sizeof node->mat);

// move tile by 1 position


swap(node->mat[x][y], node->mat[newX][newY]);

// set number of misplaced tiles


Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

node->cost = INT_MAX;

// set number of moves so far


node->level = level;

// update new blank tile coordinates


node->x = newX;
node->y = newY;

return node;
}

// bottom, left, top, right


int row[] = { 1, 0, -1, 0 };
int col[] = { 0, -1, 0, 1 };

// Function to calculate the number of misplaced tiles


// ie. number of non-blank tiles not in their goal position
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;
}

// Function to check if (x, y) is a valid matrix coordinate


int isSafe(int x, int y)
{
return (x >= 0 && x < N && y >= 0 && y < N);
}

// print path from root node to destination node


Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

void printPath(Node* root)


{
if (root == NULL)
return;
printPath(root->parent);
printMatrix(root->mat);

printf("\n");
}

// Comparison object to be used to order the heap


struct comp
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return (lhs->cost + lhs->level) > (rhs->cost + rhs->level);
}
};

// Function to solve N*N - 1 puzzle algorithm using


// Branch and Bound. x and y are blank tile coordinates
// in initial state
void solve(int initial[N][N], int x, int y,
int final[N][N])
{
// Create a priority queue to store live nodes of
// search tree;
priority_queue<Node*, std::vector<Node*>, comp> pq;

// create a root node and calculate its cost


Node* root = newNode(initial, x, y, x, y, 0, NULL);
root->cost = calculateCost(initial, final);

// Add root to list of live nodes;


pq.push(root);
Computer Engineering Department L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

// Finds a live node with least cost,


// add its childrens to list of live nodes and
// finally deletes it from the list.
while (!pq.empty())
{
// Find a live node with least estimated cost
Node* min = pq.top();

// The found node is deleted from the list of


// live nodes
pq.pop();

// if min is an answer node


if (min->cost == 0)
{
// print the path from root to destination;
printPath(min);
return;
}

// do for each child of min


// max 4 children for a node
for (int i = 0; i < 4; i++)
{
if (isSafe(min->x + row[i], min->y + col[i]))
{
// create a child node and calculate
// its cost
Node* child = newNode(min->mat, min->x,
min->y, min->x + row[i],
min->y + col[i],
min->level + 1, min);
child->cost = calculateCost(child->mat, final);

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

// Add child to list of live nodes


pq.push(child);
}
}
}
}

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

// Solvable Final configuration


// Value 0 is used for empty space
int final[N][N] =
{
{1, 2, 3},
{5, 8, 6},
{0, 7, 4}
};

// Blank tile coordinates in initial


// configuration
int x = 1, y = 2;

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

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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 :

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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)

f_score = g_score + h_score


neighbor_node = Node(neighbor_state, current_node, action, g_score, h_score)
# Check if the neighbor is already in the open list
found = False
for node in open_list:
if node.state == neighbor_state:
found = True
if g_score < node.cost:
open_list.remove(node)
heapq.heappush(open_list, neighbor_node)
break
if not found:
heapq.heappush(open_list, neighbor_node)
return None # No path found
def get_neighbors(state):
x, y = stateneighbors
= []

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:

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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:

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

Output:

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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:

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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:

Computer Engineering Department L. D. College of Engineering, Ahmedabad-15


Artificial Intelligence (3170716)

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

% Define the display predicate display_moves([Puzzle]) :-


write(Puzzle), nl. display_moves([Puzzle1,Puzzle2|T]) :-
write(Puzzle1), nl, display_moves([Puzzle2|T]).

Output:

Practical-11
Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15
Artificial Intelligence (3170716)

Aim: Write a program to solve 8 puzzle 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).

% Define the display predicate display_moves([Puzzle]) :-


write(Puzzle), nl. display_moves([Puzzle1,Puzzle2|T]) :-
write(Puzzle1), nl, display_moves([Puzzle2|T]).

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)

distance(city1, city3, 15).


distance(city2, city3, 20).
% ... (define other distances here) ...
% Define the TSP predicate tsp(Start, Path,
Cost) :-
findall(City, distance(Start, City, _), Cities),
permutation(Cities, Path1),
Path = [Start|Path1], path_cost(Path,
Cost).
% Define the path_cost predicate path_cost([_], 0).
path_cost([City1,City2|Rest], Cost) :-
distance(City1, City2, Cost1),path_cost([City2|Rest], Cost2), Cost is Cost1 + Cost2.
% Define the permutation predicate permutation([], []).
permutation(List, [H|Permutation]) :- select(H, List,
Rest), permutation(Rest, Permutation).

Output:

Computer Engineering Department, L. D. College of Engineering, Ahmedabad-15

You might also like