0% found this document useful (0 votes)
16 views

ai

Uploaded by

naresh.asus.tuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

ai

Uploaded by

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

ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 1
Aim:- Write a program to implement Tic-Tac-Toe game problem.

Code:-

import random
def drawBoard(board):
print(" ")
print(board[9]," | ",board[8]," | ",board[7])
print(" ")
print(".............")
print(" ")
print(board[6]," | ",board[5]," | ",board[4])
print(" ")
print(".............")
print(board[3]," | ",board[2]," | ",board[1])
print(" ")
print(".............")

def inputPlayerLetter():
letter = ""
while not(letter == 'X' or letter == '0'):
letter = input("Chose your symbol (0/X) : ").upper()
if letter == 'X':
return ["X","0"]

1
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

else:
return ["0","X"]

def whoGoesFirst():
if random.randint(0,1) == 0:
return 'computer'
else:
return 'player'

def playAgain():
return input("Do you want to play again? (yes/no):
").lower().startswith('y')

def makeMove(board,letter,move):
board[move] = letter

def isWinner(bo,le):
return ((bo[7] == le and bo[8] == le and bo[9]== le) or
(bo[4] == le and bo[5] == le and bo[6]== le) or
(bo[1] == le and bo[2] == le and bo[3]== le) or
(bo[7] == le and bo[4] == le and bo[1]== le) or
(bo[8] == le and bo[5] == le and bo[2]== le) or
(bo[9] == le and bo[6] == le and bo[3]== le) or
(bo[7] == le and bo[5] == le and bo[3]== le) or
(bo[9] == le and bo[5] == le and bo[1]== le) )

2
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

def getBoardCopy(board):
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard

def isSpaceFree(board,move):
return board[move] == ''

def getPlayerMove(board):
move = ''
while move not in '1 2 3 4 5 6 7 8 9'.split() or not
isSpaceFree(board,int(move)):
move = input("What is your next move ? (1-9) : ")
return int(move)

def chooseRandomMoveFromList(board,movesList):
possibleMoves = []
for i in movesList:
if isSpaceFree(board,i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None

3
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

def getComputerMove(board,computerLetter):
if computerLetter == 'X':
playerLetter == '0'
else:
playerLetter == 'X'

for i in range(1,10):
copy = getBoardCopy(board)
if isSpaceFree(copy,i):
makeMove(copy,computerLetter,i)
if isWinner(copy,computerLetter):
return i
for i in range(1,10):
copy = getBoardCopy(board)
if isSpaceFree(copy,i):
makeMove(copy,playerLetter,i)
if isWinner(copy,playerLetter):
return i
move = chooseRandomMoveFromList(board,[1,3,7,9])
if move != None:
return move

if isSpaceFree(board,5):
return 5
return chooseRandomMoveFromList(board,[2,4,6,8])

4
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

def isBoardFull(board):
for i in range(1,10):
if isSpaceFree(board,i):
return False
return True

print("............Welcome To TIC TAC TOE ..............")


while True:
theBoard = ['']*10
playerLetter,computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print(turn ," will go first")
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
drawBoard(theBoard)
move = getPlayerMove(theBoard)
makeMove(theBoard,playerLetter,move)
if isWinner(theBoard,playerLetter):
drawBoard(theBoard)
print("You won!!!")
gameIsPlaying = False
else:
if isBoardFull(theBoard):

5
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

drawBoard(theBoard)
print('It is a tie')
break
else:
turn = 'computer'
else:
move = getComputerMove(theBoard,computerLetter)
makeMove(theBoard,computerLetter,move)
if isWinner(theBoard,computerLetter):
drawBoard(theBoard)
print("Computer wins !!! You loose....")
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is Tie')
break
else:
turn = 'player'
if not playAgain():
break

Output:-

6
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

7
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 2

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


Jug problem or any AI search problem) .

Code:-

from collections import deque


class Node:
def __init__(self, board, prev_state=None):
self.board = board
self.prev = prev_state
self.step = 0 if prev_state is None else prev_state.step + 1

def __eq__(self, other):


return self.board == other.board

def __hash__(self):
return hash(tuple(self.board))

def __str__(self):
return f"{self.board[0:3]}\n{self.board[3:6]}\n{self.board[6:9]}"

def next(self):
next_moves = []
i = self.board.index(0) # Get the position of the empty space (0)

8
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right
for dx, dy in directions:
x, y = self.pos(i)
nx, ny = x + dx, y + dy
if 0 <= nx < 3 and 0 <= ny < 3: # Check boundaries
new_pos = self.sop(nx, ny)
new_board = self.board[:]
new_board[i], new_board[new_pos] = new_board[new_pos],
new_board[i] # Swap the tiles
next_moves.append(Node(new_board, self))
return next_moves

def pos(self, index):


return divmod(index, 3) # Get (row, col) of the board

def sop(self, x, y):


return x * 3 + y # Convert (row, col) back to index

def BFS(start, goal):


queue = deque([start])
visited = set()
while queue:
state = queue.popleft() # Dequeue the first element (FIFO order)
if state == goal:
print("Solution found!")
print_path(state)

9
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

return
if state not in visited:
visited.add(state)
for next_state in state.next():
if next_state not in visited:
queue.append(next_state)
print("Solution not found.")
def print_path(state):
path = []
while state:
path.append(state)
state = state.prev
path.reverse()
for step in path:
print(step)
print("---------")

# Test with a start state and goal state


start_state = Node([2, 0, 1, 4, 5, 3, 8, 7, 6]) # Starting configuration
goal_state = Node([1, 2, 3, 4, 5, 6, 7, 8, 0]) # Goal configuration

print("Starting BFS for 8-puzzle:")


BFS(start_state, goal_state)

10
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

OUTPUT:-

11
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

12
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

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

Code:-
class WaterJugState:
def __init__(self, jug1, jug2, prev=None):
self.jug1 = jug1
self.jug2 = jug2
self.prev = prev

def __eq__(self, other):


return self.jug1 == other.jug1 and self.jug2 == other.jug2

def __hash__(self):
return hash((self.jug1, self.jug2))

def __str__(self):
return f"Jug 1: {self.jug1}, Jug 2: {self.jug2}"

def next_states(self, max_jug1, max_jug2):


next_states = []

# Fill Jug 1
if self.jug1 < max_jug1:

13
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

next_states.append(WaterJugState(max_jug1, self.jug2, self))

# Fill Jug 2
if self.jug2 < max_jug2:
next_states.append(WaterJugState(self.jug1, max_jug2, self))

# Empty Jug 1
if self.jug1 > 0:
next_states.append(WaterJugState(0, self.jug2, self))

# Empty Jug 2
if self.jug2 > 0:
next_states.append(WaterJugState(self.jug1, 0, self))

# Pour from Jug 1 to Jug 2


if self.jug1 > 0 and self.jug2 < max_jug2:
pour = min(self.jug1, max_jug2 - self.jug2)
next_states.append(WaterJugState(self.jug1 - pour, self.jug2 +
pour, self))

# Pour from Jug 2 to Jug 1


if self.jug2 > 0 and self.jug1 < max_jug1:
pour = min(self.jug2, max_jug1 - self.jug1)
next_states.append(WaterJugState(self.jug1 + pour, self.jug2 -
pour, self))

14
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

return next_states

def DFS(start_state, goal, max_jug1, max_jug2):


stack = [start_state]
visited = set()
while stack:
current_state = stack.pop()
if current_state.jug1 == goal or current_state.jug2 == goal:
print_path(current_state)
print("Solution found!")
return

if current_state not in visited:


visited.add(current_state)
next_states = current_state.next_states(max_jug1, max_jug2)
for state in next_states:
stack.append(state)

print("No solution found.")

def print_path(state):
path = []
while state:

15
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

path.append(state)
state = state.prev
path.reverse()
for s in path:
print(s)

# Main
if __name__ == "__main__":
max_jug1 = 4 # Capacity of Jug 1
max_jug2 = 3 # Capacity of Jug 2
target = 2 # Target amount to measure

start_state = WaterJugState(0, 0) # Both jugs are empty initially


print("DFS for Water Jug Problem")
DFS(start_state, target, max_jug1, max_jug2)
Output:

16
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

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)
attempts += 1
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

if __name__ == "__main__":
play_game()

17
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

Output:

18
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 5

Aim:-Write a program to Implement A* Algorithm.

Code:
import heapq
class PuzzleState:
def __init__(self, board, parent=None, g=0):
self.board = board
self.parent = parent
self.g = g # Cost to reach this state from the start
self.h = self.manhattan_distance() # Heuristic value (Manhattan
Distance)
self.f = self.g + self.h # Total cost: f = g + h

def __lt__(self, other):


return self.f < other.f # Compare based on the f value for heapq

def manhattan_distance(self):
distance = 0
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
for i in range(9):
if self.board[i] == 0:
continue
current_pos = (i // 3, i % 3)

19
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

goal_pos = (goal.index(self.board[i]) // 3, goal.index(self.board[i]) %


3)
distance += abs(current_pos[0] - goal_pos[0]) + abs(current_pos[1]
- goal_pos[1])
return distance

def __eq__(self, other):


return self.board == other.board

def __hash__(self):
return hash(tuple(self.board)) # To ensure it's hashable for visited set

def get_neighbors(self):
neighbors = []
zero_pos = self.board.index(0)
x, y = zero_pos // 3, zero_pos % 3 # Find the position of 0 (blank
space)

# Possible moves for 0 (up, down, left, right)


directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < 3 and 0 <= new_y < 3:
# Make the move
new_pos = new_x * 3 + new_y
new_board = self.board[:]

20
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

new_board[zero_pos], new_board[new_pos] =
new_board[new_pos], new_board[zero_pos]
neighbors.append(PuzzleState(new_board, parent=self, g=self.g
+ 1))

return neighbors

def __str__(self):
"""For visualizing the board in a readable way"""
return "\n".join([' '.join(map(str, self.board[i:i+3])) for i in range(0, 9, 3)])

def astar_search(start_state, goal_state):


open_list = []
closed_set = set()

# Push the initial state onto the open list (heap)


heapq.heappush(open_list, (start_state.f, start_state))

while open_list:
# Pop the state with the lowest f value from the open list
_, current_state = heapq.heappop(open_list)

# If the goal state is reached, print the solution path


if current_state == goal_state:
print_solution_path(current_state)

21
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

return

# Add the current state to the closed set


closed_set.add(current_state)

# Get the neighbors of the current state


for neighbor in current_state.get_neighbors():
if neighbor in closed_set:
continue

# Add the neighbor to the open list


heapq.heappush(open_list, (neighbor.f, neighbor))

print("No solution found")

def print_solution_path(state):
path = []
while state:
path.append(state)
state = state.parent
path.reverse()

for state in path:


print("\n" + str(state))

22
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

print("Heuristic Value (Manhattan Distance):", state.h)

# Main
if __name__ == "__main__":
start_board = [2, 0, 1, 4, 5, 3, 8, 7, 6] # Example start state
goal_board = [1, 2, 3, 4, 5, 6, 7, 8, 0] # Goal state

start_state = PuzzleState(start_board)
goal_state = PuzzleState(goal_board)

print("A* Search for 8-puzzle:")


astar_search(start_state, goal_state)

Output:

23
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

24
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

25
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

26
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 6
Aim:-Write a program to implement mini-max algorithm for any game
development.
Code:
import math
# Constants for Tic-Tac-Toe
PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '

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

def is_winner(board, player):


# Check rows, columns, and diagonals for a winner
for row in board:
if all(s == player for s in row):
return True

for col in range(3):


if all(board[row][col] == player for row in range(3)):
return True

if all(board[i][i] == player for i in range(3)):

27
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

return True

if all(board[i][2-i] == player for i in range(3)):


return True

return False

def is_board_full(board):
return all(cell != EMPTY for row in board for cell in row)

def minimax(board, depth, is_max_turn):


# Base conditions: check for win or draw
if is_winner(board, PLAYER_X):
return 10 - depth
if is_winner(board, PLAYER_O):
return depth - 10
if is_board_full(board):
return 0

if is_max_turn:
max_eval = -math.inf
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
board[i][j] = PLAYER_X

28
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

eval = minimax(board, depth + 1, False)


board[i][j] = EMPTY
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = math.inf
for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
board[i][j] = PLAYER_O
eval = minimax(board, depth + 1, True)
board[i][j] = EMPTY
min_eval = min(min_eval, eval)
return min_eval

def best_move(board):
best_score = -math.inf
move = (-1, -1)

for i in range(3):
for j in range(3):
if board[i][j] == EMPTY:
board[i][j] = PLAYER_X # Maximize for X
score = minimax(board, 0, False)
board[i][j] = EMPTY

29
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

if score > best_score:


best_score = score
move = (i, j)

return move

# Main game loop


def play_game():
board = [[EMPTY] * 3 for _ in range(3)]
print("Welcome to Tic-Tac-Toe!")
print_board(board)

while True:
# Player O's turn
print("\nPlayer O's turn (minimizing):")
move = best_move(board)
board[move[0]][move[1]] = PLAYER_O
print_board(board)

if is_winner(board, PLAYER_O):
print("\nPlayer O wins!")
break
if is_board_full(board):
print("\nIt's a draw!")
break

30
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

# Player X's turn (Maximizing)


print("\nPlayer X's turn (maximizing):")
move = best_move(board)
board[move[0]][move[1]] = PLAYER_X
print_board(board)

if is_winner(board, PLAYER_X):
print("\nPlayer X wins!")
break
if is_board_full(board):
print("\nIt's a draw!")
break

if __name__ == "__main__":
play_game()

Output:

31
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

32
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

33
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

34
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

35
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 7
Aim: Assume given a set of facts of the form father (name1, name2)
(name1 is the father of name2).

Code:-

father(bob, ann).
father(bob, pat).

female(pam).
female(liz).
female(pat).
female(ann).

male(jim).
male(bob).
male(tom).
male(peter).

parent(X, Y) :- father(X, Y).


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

mother(pam, ann).
mother(liz, pat).

brother(X, Y) :- male(X), parent(P, X), parent(P, Y), X \= Y.

36
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

sister(X, Y) :- female(X), parent(P, X), parent(P, Y), X \= Y.

uncle(X, Z) :- brother(X, Y), parent(Y, Z).

Output:

37
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

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

38
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

39
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 9
Aim: Write a program to solve Tower of Hanoi problem using Prolog.
Code:

% Base case: move one disk from source to destination


hanoi(1, Source, Destination, [move(Source, Destination)]).

% Recursive case: move N disks from Source to Destination using Auxiliary


as temporary peg
hanoi(N, Source, Destination, Moves) :-
N > 1,
% N-1 disks to auxiliary peg
N1 is N - 1,
hanoi(N1, Source, auxiliary(Source, Destination), Moves1),

% Move the Nth disk from source to destination


Moves2 = [move(Source, Destination)],

% Move N-1 disks from auxiliary peg to destination


hanoi(N1, auxiliary(Source, Destination), Destination, Moves3),

% Combine all the moves


append(Moves1, Moves2, TempMoves),
append(TempMoves, Moves3, Moves).

% Define auxiliary peg

40
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

auxiliary(Source, Destination) :-
\+ Source = Destination. % Base case: move one disk from source to
destination
hanoi(1, Source, Destination, [move(Source, Destination)]).

% Recursive case: move N disks from Source to Destination using Auxiliary


as temporary peg
hanoi(N, Source, Destination, Moves) :-
N > 1,
% N-1 disks to auxiliary peg
N1 is N - 1,
hanoi(N1, Source, auxiliary(Source, Destination), Moves1),

% Move the Nth disk from source to destination


Moves2 = [move(Source, Destination)],

% Move N-1 disks from auxiliary peg to destination


hanoi(N1, auxiliary(Source, Destination), Destination, Moves3),

% Combine all the moves


append(Moves1, Moves2, TempMoves),
append(TempMoves, Moves3, Moves).

% Define auxiliary peg


auxiliary(Source, Destination) :-
\+ Source = Destination.

41
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

Output:

42
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

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

43
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

Output:

44
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 11
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]).

45
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

Output:

46
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

PRACTICAL 12
Aim: Write a program to solve travelling salesman problem using Prolog.

Code:
% Define the distances between cities
distance(city1, city2, 10).
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).

47
ARTIFICIAL INTELLIGENCE (3170716) 191390107018

Output:

48

You might also like