You are on page 1of 24

Subject Code:3170716 Subject Name:Artificial Intelligence Date:

Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:1
Problem Statement:
Write a program to take two jug capacities and a desired quantity in
either of the jug to get. Show the entire sequence to get the desired capacity.
Code:
from collections import defaultdict
jug1 = int(input("Enter the capacity of Jug1:"))
jug2 = int(input("Enter the capacity of Jug2:"))
goal = int(input("Enter the Goal range of max(jug1, jug2):"))
visited = defaultdict(lambda: False)
def waterjugproblem(amount1, amount2):
if max(amount1, amount2) == goal:
print("Here is your goal")
print(amount1, amount2)
return True
if visited[(amount1, amount2)] == False:
print(amount1, amount2)
visited[(amount1, amount2)] = True
return (waterjugproblem(0, amount2) or waterjugproblem(amount1, 0) or
waterjugproblem(jug1, amount2) or
waterjugproblem(amount1, jug2) or
waterjugproblem(amount1 + min(amount2, (jug1 - amount1)),
amount2 - min(amount2, (jug1 - amount1))) or
waterjugproblem(amount1 - min(amount1, (jug2 - amount2)),
amount2 + min(amount1, (jug2 - amount2))))
else:
return False
print("Here are the steps:")
waterjugproblem(0, 0)

Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 1
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:2
Problem Statement:
Introduction to Prolog.
1.Write a prolog program for parent relationship.
Code:
parent(elizabeth,charles).
parent(philip,charles).
parent(elizabeth,anne).
parent(philip,anne).
parent(elizabeth,andrew).
parent(philip,andrew).
parent(diana,william).
parent(charles,william).
parent(diana,harry).
parent(charles,harry).

Output:

Problem Statement:
2. Write a Prolog program to assert parent relationship along with
gender facts. ( Hint: Use predicates: parent, male, female OR parent,
gender) - Use family tree provided at slide no-17 to assert facts.
Code:
male(paul).
male(vernon).
male(albert).
male(lili).
female(helen).
female(petunia).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 2
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

female(james).
female(ruth).
parent(paul,petunia).
parent(paul,lili).
parent(vernon,dudley).
parent(lili,harry).
parent(albert,james).
parent(helen,petunia).
parent(helen,lili).
parent(petunia,dudley).
parent(james,harry).
parent(ruth,james).

Output:

Problem Statement:
3. Write a Prolog program for directed graph-1. (Use graphs
from slide-19.)
Code:
edge(a,b).
edge(b,c).
edge(c,e) .
edge(e,f) .
edge(e,d).
edge(d,b).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 3
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Output:

Problem Statement:
4. Write a Prolog program for directed graph-2. (as per slide-20 (A))
Code:
edge(a,b).
edge(a,c).
edge(a,d).
edge(b,d).
edge(c,e).
edge(c,d).
edge(d,e).
edge(e,a).

Output:

Problem Statement:
5. Write a Prolog program for undirected graph. ( as per slide-20 (B))
Code:
edge(a,b).
edge(b,a).
edge(b,c).
edge(c,b).
edge(c,e).
edge(e,c).
edge(c,d).
edge(d,c).
edge(d,e).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 4
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

edge(e,d).
edge(d,f).
edge(f,d).
edge(e,f).
edge(f,e).
edge(d,g).
edge(g,d).

Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 5
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:3
Problem Statement:
Rules in Prolog.
1. Write a Prolog Program for basic relationship rules. (slide No-5)
Code:
parent(elizabeth,charles).
parent(philip,charles).
parent(elizabeth,anne).
parent(philip,anne).
parent(elizabeth,andrew).
parent(philip,andrew).
parent(diana,william).
parent(charles,william).
parent(diana,harry).
parent(charles,harry).
male(philip).
male(charles).
male(andrew).
female(anne).
female(diana).
female(elizabeth).
child(X,Y) :- parent(Y,X).
mother(X,Y) :- parent(X,Y), female(X).
father(X,Y) :- parent(X,Y), male(X).
son(X,Y) :- child(X,Y), male(X).
daughter(X,Y) :- child(X,Y), female(X).
sibling(X,Y) :- parent(Z,X), parent(Z,Y).

Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 6
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Problem Statement:
2. Write a Prolog Program to add relations - Uncle, Aunt, Nephew,
Niece,grandfather, Grandmother, Grand Child, Cousin in previous program.
Code:
parent(elizabeth,charles).
parent(philip,charles).
parent(elizabeth,anne).
parent(philip,anne).
parent(elizabeth,andrew).
parent(philip,andrew).
parent(diana,william).
parent(charles,william).
parent(diana,harry).
parent(charles,harry).
parent(stephen,philip).
parent(stephen,damon).
parent(damon,noah).
parent(elina,noah).
male(philip).
male(charles).
male(andrew).
male(stephen).
male(damon).
male(noah).
female(elina).
female(anne).
female(diana).
female(elizabeth).
child(X,Y) :- parent(Y,X).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 7
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

mother(X,Y) :- parent(X,Y), female(X).


father(X,Y) :- parent(X,Y), male(X).
son(X,Y) :- child(X,Y), male(X).
daughter(X,Y) :- child(X,Y), female(X).
sibling(X,Y) :- parent(Z,X), parent(Z,Y), not(X=Y).
uncle(X,Y) :- sibling(Z,X),parent(Z,Y),male(Z),male(X).
cousin(X,Y) :- sibling(A,B),parent(A,X),parent(B,Y).
aunt(X,Y) :- cousin(Y,Z),parent(X,Z),female(X).
nephew(X,Y) :- uncle(Y,X),male(X).
niece(X,Y) :- uncle(Y,X),female(X).
grandfather(X,Y) :- parent(X,Z),parent(Z,Y),male(X).
grandmother(X,Y) :- parent(X,Z),parent(Z,Y),female(X).
grandchild(X,Y) :- grandfather(Y,X);grandmother(Y,X).

Output:

Problem Statement:
3. Write a Prolog Program for recursive rule for relationship ( slide No-8,9)
Code:
parent(john,paul).
parent(paul,tom).
parent(tom,mary).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 8
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

ancestor(X,Y) :- parent(X,Y).
ancestor(X,Y) :- parent(X,Z),ancestor(Z,Y).
child(X,Y) :- parent(Y,X).
descendants(X,Y) :- child(X,Y).
descendants(X,Y) :- child(X,Z), descendants(Z,Y).
Output:

Problem Statement:
4. Write a Prolog Program for recursive rule for directed graph (slide No- 11)
Code:
edge(a,b).
edge(b,c).
edge(b,d).
edge(b,e).
edge(g,d).
edge(d,e).
edge(c,e).
edge(e,f).
connected(X,Y) :- edge(X,Y).
connected(X,Z) :- edge(X,Y),connected(Y,Z).

Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 9
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:4
Problem Statement:
Write a program to implement BFS (for 8 puzzle problem or Water Jug
problem or any AI search problem)
Code:
from collections import deque

print("The capacity of jug 1: 4")


print("The capacity of jug 2: 3")

def BFS(a, b, target):


m = {}
isSolvable = False
path = []
q = deque()
q.append((0, 0))
while len(q) > 0:
u = q.popleft()
if (u[0], u[1]) in m:
continue
if ((u[0] > a or u[1] > b or u[0] < 0 or u[1] < 0)):
continue
path.append([u[0], u[1]])
m[(u[0], u[1])] = 1
if u[0] == target or u[1] == target:
isSolvable = True
if u[0] == target:
if u[1] != 0:
path.append([u[0], 0])
else:
if u[0] != 0:
path.append([0, u[1]])
sz = len(path)
for i in range(sz):
print("Jug 1:", path[i][0], ", Jug 2:", path[i][1])
break
q.append([u[0], b])
q.append([a, u[1]])
for ap in range(max(a, b) + 1):
c = u[0] + ap
d = u[1] - ap
if c == a or (d == 0 and d >= 0):
q.append([c, d])

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 10
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

c = u[0] - ap
d = u[1] + ap
if (c == 0 and c >= 0) or d == b:
q.append([c, d])
q.append([a, 0])
q.append([0, b])
if not isSolvable:
print("No solution")
if __name__ == '__main__':
Jug1, Jug2, target = 4, 3, 2
print("Steps to achieve the target amount:")
BFS(Jug1, Jug2, target)

Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 11
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:5
Problem Statement:
Write a program to implement DFS (for 8 puzzle problem or Water Jug
problem or any AI search problem)
Code:
print("The capacity of jug 1: 4")
print("The capacity of jug 2: 3")

def DFS(a, b, target, visited, path):


if (a, b) in visited:
return False

path.append((a, b))
visited.add((a, b))

if a == target or b == target:
return True

# Fill Jug 1 to its capacity


if a < 4:
if DFS(4, b, target, visited, path):
return True

# Fill Jug 2 to its capacity


if b < 3:
if DFS(a, 3, target, visited, path):
return True

# Empty Jug 1
if a > 0:
if DFS(0, b, target, visited, path):
return True

# Empty Jug 2
if b > 0:
if DFS(a, 0, target, visited, path):
return True

# Pour from Jug 1 to Jug 2


if a > 0 and b < 3:
pour = min(a, 3 - b)
if DFS(a - pour, b + pour, target, visited, path):
return True

# Pour from Jug 2 to Jug 1


if b > 0 and a < 4:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 12
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel
pour = min(b, 4 - a)
if DFS(a + pour, b - pour, target, visited, path):
return True

# No solution found
path.pop()
return False

if __name__ == '__main__':
Jug1, Jug2, target = 4, 3, 2
visited = set()
path = []

print("Steps to achieve the target amount:")


if DFS(0, 0, target, visited, path):
for step in path:
print("Jug 1:", step[0], ", Jug 2:", step[1])
else:
print("No solution")
Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 13
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:6
Problem Statement:
Write a program to Implement A* Algorithm.
Code:
import heapq

# Define a class to represent the nodes in the search tree


class Node:
def __init__(self, state, parent, cost, heuristic):
self.state = state # The current state
self.parent = parent # Parent node
self.cost = cost # Cost to reach this node
self.heuristic = heuristic # Heuristic value
self.priority = cost + heuristic # Priority value for the priority queue

def __lt__(self, other):


return self.priority < other.priority

# A* search function
def astar_search(initial_state, goal_state, get_successors, heuristic):
open_set = [] # Priority queue (min-heap) for nodes to be explored
closed_set = set() # Set to store visited states

# Create the initial node


initial_node = Node(initial_state, None, 0, heuristic(initial_state, goal_state))

# Add the initial node to the open set


heapq.heappush(open_set, initial_node)

while open_set:
current_node = heapq.heappop(open_set)

# Check if the current state is the goal state


if current_node.state == goal_state:
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
return list(reversed(path))

# Add the current state to the closed set


closed_set.add(current_node.state)

# Generate successor states and add them to the open set


for successor_state, step_cost in get_successors(current_node.state):
if successor_state in closed_set:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 14
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel
continue

# Calculate the cost and heuristic values for the successor node
successor_cost = current_node.cost + step_cost
successor_heuristic = heuristic(successor_state, goal_state)

# Create the successor node


successor_node = Node(successor_state, current_node, successor_cost,
successor_heuristic)

# Add the successor node to the open set


heapq.heappush(open_set, successor_node)

# If the open set becomes empty and the goal is not reached, there is no solution
return None

# Define a sample heuristic function (you can customize this)


def simple_heuristic(state, goal_state):
return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])

# Define a sample get_successors function (you can customize this)


def get_successors(state):
x, y = state
successors = []
# Define possible moves (up, down, left, right)
moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for dx, dy in moves:
new_x, new_y = x + dx, y + dy
# Check if the new state is valid (within bounds)
if 0 <= new_x <= 5 and 0 <= new_y <= 5:
successors.append(((new_x, new_y), 1)) # Step cost is 1 for simplicity
return successors

if __name__ == '__main__':
initial_state = (0, 0)
goal_state = (5, 5)
path = astar_search(initial_state, goal_state, get_successors, simple_heuristic)

if path:
print("Path from", initial_state, "to", goal_state, ":", path)
else:
print("No path found.")
Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 15
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:7
Problem Statement:
Write a program to implement mini-max algorithm for any game
development.
Code:
# Define the tic-tac-toe board as a 3x3 grid
board = [[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']]

# Function to print the tic-tac-toe board


def print_board(board):
for row in board:
print("|".join(row))
print("-----")

# Function to check if the game is over


def is_game_over(board):
# Check for a win
for row in board:
if row.count(row[0]) == 3 and row[0] != ' ':
return True
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] and board[0][col] != ' ':
return True
if board[0][0] == board[1][1] == board[2][2] and board[0][0] != ' ':
return True
if board[0][2] == board[1][1] == board[2][0] and board[0][2] != ' ':
return True

# Check for a tie


if all(cell != ' ' for row in board for cell in row):
return True

return False

# Minimax algorithm
def minimax(board, depth, is_maximizing):
if is_game_over(board):
if is_maximizing:
return -1 # Opponent wins
else:
return 1 # AI wins
elif is_maximizing:
max_eval = -float('inf')
for i in range(3):

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 16
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
eval = minimax(board, depth + 1, False)
board[i][j] = ' '
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
eval = minimax(board, depth + 1, True)
board[i][j] = ' '
min_eval = min(min_eval, eval)
return min_eval

# Find the best move using the Minimax algorithm


def find_best_move(board):
best_eval = -float('inf')
best_move = None

for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
eval = minimax(board, 0, False)
board[i][j] = ' '
if eval > best_eval:
best_eval = eval
best_move = (i, j)

return best_move

# Main game loop


while not is_game_over(board):
print_board(board)
player_move = tuple(map(int, input("Enter your move (row and column):
").split()))
if board[player_move[0]][player_move[1]] == ' ':
board[player_move[0]][player_move[1]] = 'X'
else:
print("Invalid move. Try again.")
continue

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 17
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel
if is_game_over(board):
break

ai_move = find_best_move(board)
board[ai_move[0]][ai_move[1]] = 'O'

print_board(board)

# Determine the winner


if is_game_over(board):
if minimax(board, 0, True) == 1:
print("AI wins!")
elif minimax(board, 0, True) == -1:
print("Player wins!")
else:
print("It's a tie!")
Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 18
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:8
Problem Statement:
Write a program to solve Tower of Hanoi problem using Prolog.
Code:
hanoi(N) :- move(N, left, right, center).
move(1, A, B, _) :-
write('Move top disk from '), write(A), write(' to '), write(B), nl.
move(N, A, B, C) :-
N1 is N - 1,
move(N1, A, C, B),
move(1, A, B, _),
move(N1, C, B, A).
Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 19
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:9
Problem Statement:
Write a program to solve N-Queens problem using Prolog.
Code:
% N-Queens problem solver
n_queens(N, Solution) :-
range(1, N, Rows),
permutation(Rows, Solution),
is_safe(Solution).

% Generate a range of integers


range(Start, End, []) :- Start > End.
range(Start, End, [Start|Rest]) :-
Start =< End,
Next is Start + 1,
range(Next, End, Rest).

% Permutation of a list
permutation([], []).
permutation(List, [H|PermRest]) :-
select(H, List, Rest),
permutation(Rest, PermRest).

% Check if a placement is safe


is_safe([]).
is_safe([X|Xs]) :-
safe(X, Xs, 1),
is_safe(Xs).

safe(_, [], _).


safe(X, [Y|Ys], N) :-
X \= Y,
X + N =\= Y,
X - N =\= Y,
NextN is N + 1,
safe(X, Ys, NextN).

% Example usage:
% n_queens(8, Solution) will solve the 8-Queens problem and return the solution.
Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 20
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:10
Problem Statement:
Write a program to solve 8 puzzle problem using Prolog.
Code:
% Define the predicate move, which takes a list of integers representing the current
state of the puzzle
% and returns a list of integers representing the new state of the puzzle after a valid
move.
move([X1,0,X3,X4,X5,X6,X7,X8,X9], [0,X1,X3,X4,X5,X6,X7,X8,X9]).
move([X1,X2,X3,0,X5,X6,X7,X8,X9], [X1,X2,X3,X5,0,X6,X7,X8,X9]).
move([X1,X2,X3,X4,0,X6,X7,X8,X9], [X1,X2,X3,X4,X6,0,X7,X8,X9]).
move([X1,X2,X3,X4,X5,0,X7,X8,X9], [X1,X2,X3,X4,X5,X7,0,X8,X9]).
move([X1,X2,X3,X4,X5,X6,0,X8,X9], [X1,X2,X3,X4,X5,X6,X8,0,X9]).
move([X1,X2,X3,X4,X5,X6,X7,0,X9], [X1,X2,X3,X4,X5,X6,X7,X9,0]).
move([X1,X2,X3,X4,X5,X6,X7,X8,0], [X1,X2,X3,X4,X5,X6,X7,0,X8]).
move([X1,X2,X3,X4,X5,X6,X7,X8,X9], [X1,X2,X3,X4,X5,X6,X7,X9,X8]).

% Define the predicate solve, which takes a list of integers representing the current
state of the puzzle
% and a list of integers representing the goal state of the puzzle.
solve(State, Goal) :-
bfs([[State]], [], Path),
reverse(Path, Goal).

% Define the predicate bfs, which takes a list of lists representing the frontier,
% a list of integers representing the explored set, and a list of lists representing the
path to the goal.
bfs([[State|Path]|_], _, [State|Path]) :-
State = [0,1,2,3,4,5,6,7,8].
bfs([Path|Paths], Explored, Solution) :-
last(Path, State),
findall([NewState, State|Path], (move(State, NewState), \+ member(NewState,
Explored)),
NewPaths),
append(Paths, NewPaths, Frontier),
append(Explored, [State], NewExplored),
bfs(Frontier, NewExplored, Solution).

% Define the predicate find_solution, which takes a list of integers representing the
current state of the puzzle
% and prints the solution.
find_solution(State) :-
Goal = [0,1,2,3,4,5,6,7,8],
solve(State, Solution),
write('Solution: '), nl,
print_solution(Solution).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 21
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

% Define the predicate print_solution, which takes a list of lists representing the path
to the goal
% and prints the solution.
print_solution([]).
print_solution([State|Path]) :-
print_state(State), nl,
print_solution(Path).

% Define the predicate print_state, which takes a list of integers representing the
current state of the puzzle
% and prints the state.
print_state([X1,X2,X3,X4,X5,X6,X7,X8,X9]) :-
write([X1,X2,X3]), nl,
write([X4,X5,X6]), nl,
write([X7,X8,X9]), nl, nl.

% Example usage:
% find_solution([1, 2, 3, 0, 4, 5, 6, 7, 8]) will solve the 8-puzzle problem with the
given initial state.
Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 22
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel

Practical No:11
Problem Statement:
Write a program to solve travelling salesman problem using Prolog.
Code:
% Define the distance between cities
distance(city(a, 0, 0), city(b, 1, 1), 2).
distance(city(b, 1, 1), city(c, 2, 2), 2).
distance(city(c, 2, 2), city(d, 3, 3), 2).
distance(city(d, 3, 3), city(e, 4, 4), 2).
distance(city(e, 4, 4), city(a, 0, 0), 4).
% Define the cities

city(a, 0, 0).
city(b, 1, 1).
city(c, 2, 2).
city(d, 3, 3).
city(e, 4, 4).

% Find the shortest tour


tsp(Cities, Tour, Distance) :-
permutation(Cities, Tour),
calculate_total_distance(Tour, Distance).
calculate_total_distance([_], 0).
calculate_total_distance([City1, City2 | Rest], TotalDistance) :-
distance(City1, City2, Distance),
calculate_total_distance([City2 | Rest], RemainingDistance),
TotalDistance is Distance + RemainingDistance.

% Find the optimal tour and distance


find_optimal_tour(OptimalTour, OptimalDistance) :-
setof([Tour, Distance], tsp([city(a,0,0),city(b,1,1),city(c,2,2),city(d,3,3),city(e,4,4)],
Tour, Distance), Tours),

min_distance_tour(Tours, OptimalTour, OptimalDistance).

min_distance_tour([[Tour, Distance]], Tour, Distance).

min_distance_tour([[Tour1, Distance1], [Tour2, Distance2] | Rest],


OptimalTour, OptimalDistance) :-

(Distance1 < Distance2 ->min_distance_tour([[Tour1, Distance1] | Rest],


OptimalTour, OptimalDistance);

min_distance_tour([[Tour2, Distance2] | Rest], OptimalTour, OptimalDistance) ).

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 23
Subject Code:3170716 Subject Name:Artificial Intelligence Date:
Enrollment No:200420107052 Name:Devangi K. Patel
% Find the optimal tour and print the result
find_and_print_optimal_tour :-
find_optimal_tour(OptimalTour, OptimalDistance),
write('Optimal Tour: '), write(OptimalTour), nl,
write('Optimal Distance: '), write(OptimalDistance), nl.

% Run the program


find_and_print_optimal_tour.

Output:

SCET/CO/2023-24/Odd/BE Div-I/Sem-VII 24

You might also like