0% found this document useful (0 votes)
3 views40 pages

Batch 2 - Ai Record - Merged

The document is a practical laboratory record for the Artificial Intelligence course at Sri Sai Ram Engineering College, detailing various experiments conducted during the academic year 2022-2023. It includes an index of experiments, aims, descriptions, and results for each exercise, such as studying Prolog, solving the 4-Queens problem, and the 8-puzzle problem. Each experiment outlines the objectives and provides the Prolog code used to achieve the results.

Uploaded by

bujjiksofficial
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)
3 views40 pages

Batch 2 - Ai Record - Merged

The document is a practical laboratory record for the Artificial Intelligence course at Sri Sai Ram Engineering College, detailing various experiments conducted during the academic year 2022-2023. It includes an index of experiments, aims, descriptions, and results for each exercise, such as studying Prolog, solving the 4-Queens problem, and the 8-puzzle problem. Each experiment outlines the objectives and provides the Prolog code used to achieve the results.

Uploaded by

bujjiksofficial
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/ 40

NAME :

REGISTER NO.:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

III YEAR/ VI SEMESTER

20CSPL601 - ARTIFICIAL INTELLIGENCE LABORATORY

MAY - 2023
Department of Computer Science and Engineering

Bonafide Certificate
REGISTER NUMBER

This is to certify the bonafide record of the work done by

__ Register No. of B.E.,

Computer Science & Engineering during the academic year 2022-2023.

Subject: ARTIFICIAL INTELLIGENCE LABORATORY


Subject Code: 20CSPL601

Staff In-Charge Head of the Department

Submitted for the Third Year / Sixth Semester - End Semester Practical
Examination held on at Sri Sai Ram Engineering
College, Chennai-600044.

Internal Examiner External Examiner


`

INDEX

EXP DATE EXPERIMENT TITLE PAGE NO SIGNATURE


NO

1 03/02/23 STUDY OF PROLOG 1

2 08/02/23 WRITE SIMPLE FACT FOR 8


STATEMENTS USING PROLOG
WRITE PREDICATES ONE CONVERTS
3 15/02/23 CENTIGRADE TO FAHRENHEIT AND 9
OTHER CHECKS IF A TEMPERATURE
IS BELOW FREEZING

4 22/02/23 4-QUEEN PROBLEM 10

5 01/03/23 8-PUZZLE PROBLEM 14

6 11/03/23 BREADTH FIRST SEARCH 21

7 15/03/23 DEPTH FIRST SEARCH 22

8 29/03/23 TRAVELLING SALESMAN PROBLEM 23

9 01/04/23 WATER JUG PROBLEM 25

10 21/04/23 MISSIONARIES AND CANNIBAL 30


PROBLEM

11 03/05/23 LIBRARY MANAGEMENT SYSTEM 36


EX NO : 1 STUDY OF PROLOG
DATE : 03/02/2023

AIM:
To Study about Prolog.

STUDY:
symbolic, non-numeric computation. suited for solving problems that involve objects and relations
between objects.

Tom is a parent of Bob can be written in Prolog as:


parent(tom, bob).
parent as the name of a relation; tom and bob are its arguments.
The whole Family Tree
parent(pam, bob).
parent(tom, bob).
parent(tom, liz).
parent(bob, ann).
parent(bob, pat).
parent(pat, jim).
This program consists of six clauses.
Prolog can be posed some questions about the parent relation

OUTPUT:
?- parent(bob,pat).
true.
?- parent(liz,pat).
false.
?- parent(tom,ben).
false.

1
?- parent(X,liz).
X = tom.
?- parent( bob, X).
X = ann .
?- parent( bob, X).
X = ann ;
X = pat.
?- parent(X, Y).
X = pam,
Y = bob ;
X = tom,
Y = bob ;
X = tom,
Y = liz ;
X = bob,
Y = ann ;
X = bob,
Y = pat ;
X = pat,
Y = jim.

The GRANDPARENT relation expressed as a composition of two parent relations.

(1) Who is a parent of Jim? Assume that this is


some Y.
(2) Who is a parent of Y? Assume that this is
some X.
?- parent( Y, jim), parent( X, Y).
Y = pat,
X = bob
̍?- parent( tom, X), parent( X, Y).

2
X = bob,
Y = ann ;
X = bob,
Y = pat ;
Adding grandparent relation to the existing
program
grandparent(X,Y):-parent(X,Z),parent(Z,Y).
?- grandparent(pam,pat).
true.
?- grandparent(pam,ann).
true.
?- grandparent(tom,ann).
true .

EXERCISES
1. parent(jim,X)
2. parent(X,jim)
3. parent(pam,X),parent(X,pat)
4. parent(pam,X),parent(X,Y),parent(Y,jim)
5. Who is Pat's parent?
6. Does Liz have a child?
7. Who is Pat's grandparent?

EXTENDING THE EXAMPLES:


female( pam).
male( tom).
male( bob).
female( liz).
female( pat).
female( ann).
male( jim).
The relations introduced here are MALE and FEMALE. These relations are unary relations. Unary
relations can be used to declare simple yes/no properties of objects

OUTPUT:
?- male(jim).
true.
?- female(pam).
true.
?- female(liz).
true.
?- male(X).
X = tom ;
X = bob ;

3
X = jim.
Let us introduce the CHILDREN relation as the inverse of the parent relation.
For all X and Y, Y is a child of X if X is a parent of Y.
child( Y, X) :- parent( X, Y). → Rules
OUTPUT:
?- child(liz,tom).
true.
?- child(X,tom).
X = bob ;
X = liz.

Rules specify things that may be true if some condition is satisfied.


Rules have a condition part (the right-hand side of the
rule)(body) and a conclusion part (the left-hand side of the rule).
(head)
Let us Introduce MOTHER relation For all X and Y.
X is the mother of Y if X is a parent of Y and X is a female.
mother( X, Y) :- parent( X, Y), female( X).

OUTPUT:
?- mother(pam,bob).
true .
?- mother(X,bob).
X = pam ;
false.
?- mother(X,Y).
X = pam,
Y = bob ;
X = pat,
Y = jim.

Exercise:
Introduce Sister Relation in your program
Some important points
• Prolog programs can be extended by simply adding new clauses.
• Prolog clauses are of three types: facts, rules and questions.
• Facts declare things that are always, unconditionally true.
• Rules declare things that are true depending on a given condition.
• By means of questions the user can ask the program what things are true. Prolog clauses consist
of the head and the body. The body is a list of goals separated by commas. Commas are
understood as conjunctions
• A variable can be substituted by another object. we say that a variable becomes instantiated.
• Variables are assumed to be universally quantified and are read as “for all”.

4
Exercise:
1. Translate the following statements into prolog rules.
2. Everybody who has a child is happy
3. For all X, if X has a child who has a sister, then X has two children
4. Define the relation grandchild using the parent relation
5. Define the relation aunt(X, Y) in terms of the relations parent and sister

A RECURSIVE RULE DEFINITION:

(a) X is a direct predecessor of Z;


(b) X is an indirect predecessor of. Z.
For all X and Z, X is a predecessor of. Z if X is a
parent of Z.
predecessor(X, Z) :- parent( X, Z).

predecessor(X, Z) :- parent( X, Y1), parent( Yl,


Y2), parent( Y2, Y3), parent( Y3, Z).
This program is lengthy and, more importantly, it only works to some extent
Recursive Definitions
predecessor(X, Z) :- parent( X, Z).
predecessor(X, Z) :- parent( X, Y), predecessor(Y,Z).
STRUCTURES: Structured objects (or simply structures) are objects that have several
Components.

5
date( 1, may, 1983)

date(Day, may, 1983) – Any Day in May


p1 : point(l,l)
p2: point(2,3)
S : seg( Pl, P2): seg( point(l,1), point(2,3))
T : triangle( point(4,Z), point(6,4), point(7,l) )

MATCHING:
Given two terms, we say that they match if they are identical, or the variables in both terms can
be instantiated to objects in such a way that after the substitution of variables by these objects
the terms become identical.
?- date(D1,M1,1983)=date(D,M,Y1).
D1 = D,
M1 = M,
Y1 = 1983.
?- date(D1,M1,1983)=date(D,M,1987).
false.
?-
date(D,M,1983)=date(D1,may,Y1),date(D,M,1983
)=date(15,M,Y).
D = D1, D1 = 15,
M = may,
Y1 = Y, Y = 1983.

6
vertical(seg(point(X,Y),point(X,Y1))).
horizontal(seg(point(X,Y),point(X1,Y))).
Output:
?-
| vertical(seg(point(1,4),point(1,5))).
true.
?- horizontal(seg(point(2,10),point(10,10))).
true.
?- horizontal(seg(point(1,5),point(5,Y))).
Y = 5.
?- vertical( seg( point(2,3), P) ).
P = point(2, _).
?- vertical(S),horizontal(S).
S = seg(point(_A, _B), point(_A, _B)).

RESULT:
Thus, Basics of Prolog was studied Successfully.

7
EX NO : 2 WRITE SIMPLE FACT FOR STATEMENTS USING PROLOG
DATE : 08/02/2023

AIM:

To write simple facts for statements using prolog.

DESCRIPTION:

Write simple fact for following:


a. Ram likes mango.
b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.

CLAUSES:

likes(ram,mango).
girl(seema).
red(rose).
likes(bill ,cindy).
owns(john ,gold).

OUTPUT:

?-likes(ram,What).
What= mango
?-likes(Who,cindy).
Who= cindy
?-red(What).
What= rose
?-owns(Who,What).
Who= john
What= gold.

RESULT:
Thus, the facts for statements have been executed successfully and the output is
verified.

8
EX NO:3
DATE : 15/02/2023

WRITE PREDICATES ONE CONVERTS CENTIGRADE TO FAHRENHEIT AND


OTHER CHECKS IF A TEMPERATURE IS BELOW FREEZING

AIM:

To write predicates one converts centigrade to fahrenheit and other checks if


temperature is below freezing,

PROGRAM:

PRODUCTION RULES-
c_to_f (F,C) F is C * 9 / 5 +32
freezing f < = 32

CLAUSES-
c_to_f(C,F) :-
F is C * 9 /
5 + 32.
freezing(F)
:-
F =< 32.

OUTPUT:

RESULT:
Thus, the Program for writing predicates to convert centigrade to Fahrenheit and
other checking if temperature is below freezing has been executed successfully.

9
EX NO:4 4-QUEEN PROBLEM
DATE : 22/02/2023

AIM:

To write a program to solve the 4-Queens Problem.

DESCRIPTION:

In the 4 Queens problem the object is to place 4 queens on a chessboard in such a way that no
queens can capture a piece. This means that no two queens may be placed on the same row, column,
or diagonal.

Fig1: The n Queens Chessboard.

PROGRAM:

queens(N,Queens) :-
length(Queens, N),
board(Queens, Board,0, N, _, _),queens(Board,0, Queens).
board([], [], N, N, _, _).
board([_|Queens], [Col-Vars|Board], Col0, N, [_|VR], VC):-
Col is Col0+1,
functor(Vars, f, N),
constraints(N, Vars,
VR, VC),
board(Queens, Board, Col,
N, VR, [_|VC]). constraints(0, _, _,
_) :- !.
constraints(N, Row, [R|Rs],
[C|Cs]) :-arg(N, Row,
R-C),

10
M is N-1,
constraints(M, Row,
Rs, Cs).queens([], _, []).
queens([C|Cs], Row0,
[Col|Solution]) :-Row
is Row 0+1,
select(Col-Vars,[C|Cs],
Board),arg(Row, Vars,
Row-Row),
queens(Board, Row,Solution).

OUTPUT:

PROGRAM
# Python program to solve N Queen
# Problem using backtracking
global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()
def isSafe(board, row, col):
# Check this row on left side
for i in range(col):

11
if board[row][i] == 1:
return False
# Check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# Check lower diagonal on left side
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col):
# base case: If all queens are placed
# then return true
if col >= N:
return True
# Consider this column and try placing
# this queen in all rows one by one
for i in range(N):
if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
# recur to place rest of the queens
if solveNQUtil(board, col + 1) == True:
return True
# If placing queen in board[i][col
# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0
# if the queen can not be placed in any row in
# this column col then return false
return False
# This function solves the N Queen problem using
# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.

12
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
# driver program to test above function
solveNQ()

OUTPUT:

0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0

RESULT:
Thus, the Program for the 4-Queens Problem has been executed successfully and the
output is verified.

13
EX NO:5 8 PUZZLE PROBLEM
DATE : 01/03/2023

AIM:
To write a program to solve the 8 puzzle problem.

PROLOG PROGRAM:

% Simple Prolog Planner for the 8 Puzzle Problem


% This predicate initializes the problem states. The first argument
% of solve/3 is the initial state, the 2nd the goal state, and the
% third the plan that will be produced.

test(Plan):-
write('Initial state:'),nl, Init= [at(tile4,1), at(tile3,2), at(tile8,3), at(empty,4), at(tile2,5), at(tile6,6),
at(tile5,7), at(tile1,8), at(tile7,9)],
write_sol(Init),
Goal= [at(tile1,1), at(tile2,2), at(tile3,3), at(tile4,4), at(empty,5), at(tile5,6), at(tile6,7), at(tile7,8),
at(tile8,9)],
nl,write('Goal state:'),nl,
write(Goal),nl,nl,
solve(Init,Goal,Plan).

solve(State, Goal, Plan):-


solve(State, Goal, [], Plan).

%Determines whether Current and Destination tiles are a valid move.


is_movable(X1,Y1) :- (1 is X1 - Y1) ; (-1 is X1 - Y1) ; (3 is X1 - Y1) ; (-3 is X1 - Y1).

% This predicate produces the plan. Once the Goal list is a subset
% of the current State the plan is complete and it is written to
% the screen using write_sol/1.

solve(State, Goal, Plan, Plan):-


is_subset(Goal, State), nl,
write_sol(Plan).

solve(State, Goal, Sofar, Plan):-


act(Action, Preconditions, Delete, Add),
is_subset(Preconditions, State),
\+ member(Action, Sofar),

14
delete_list(Delete, State, Remainder), append(Add, Remainder, NewState), solve(NewState,
Goal, [Action|Sofar], Plan).

% The problem has three operators.


% 1st arg = name
% 2nd arg = preconditions
% 3rd arg = delete list
% 4th arg = add list.
% Tile can move to new position only if the destination tile is empty & Manhattan distance = 1
act(move(X,Y,Z),
[at(X,Y), at(empty,Z), is_movable(Y,Z)],
[at(X,Y), at(empty,Z)],
[at(X,Z), at(empty,Y)]).
% Utility predicates.
% Check is first list is a subset of the second

is_subset([H|T], Set):-
member(H, Set),
is_subset(T, Set).
is_subset([], _).

% Remove all elements of 1st list from second to create third.

delete_list([H|T], Curstate, Newstate):-


remove(H, Curstate, Remainder),
delete_list(T, Remainder, Newstate).
delete_list([], Curstate, Curstate).

remove(X, [X|T], T).


remove(X, [H|T], [H|R]):-
remove(X, T, R).

write_sol([]).
write_sol([H|T]):-
write_sol(T),
write(H), nl.

append([H|T], L1, [H|L2]):-


append(T, L1, L2).
append([], L, L).

member(X, [X|_]).
member(X, [_|T]):-
member(X, T).

15
PYTHON PROGRAM:

Python code to display the way from the root


# node to the final destination node for N*N-1 puzzle
# algorithm by the help of Branch and Bound technique
# The answer assumes that the instance of the
# puzzle can be solved
# Importing the 'copy' for deepcopy method
import copy
# Importing the heap methods from the python
# library for the Priority Queue
from heap import heappush, heappop
# This particular var can be changed to transform
# the program from 8 puzzle(n=3) into 15
# puzzle(n=4) and so on ...
n=3
# bottom, left, top, right
rows = [ 1, 0, -1, 0 ]
cols = [ 0, -1, 0, 1 ]
# creating a class for the Priority Queue
class priorityQueue:
# Constructor for initializing a
# Priority Queue
def __init__(self):
self.heap = []
# Inserting a new key 'key'
def push(self, key):
heappush(self.heap, key)
# funct to remove the element that is minimum,
# from the Priority Queue
def pop(self):
return heappop(self.heap)
# funct to check if the Queue is empty or not
def empty(self):
if not self.heap:
return True
else:
return False
# structure of the node
class nodes:
def __init__(self, parent, mats, empty_tile_posi,

16
costs, levels):
# This will store the parent node to the
# current node And helps in tracing the
# path when the solution is visible
self.parent = parent
# Useful for Storing the matrix
self.mats = mats
# useful for Storing the position where the
# empty space tile is already existing in the matrix
self.empty_tile_posi = empty_tile_posi
# Store no. of misplaced tiles
self.costs = costs
# Store no. of moves so far
self.levels = levels
# This func is used in order to form the
# priority queue based on
# the costs var of objects
def __lt__(self, nxt):
return self.costs < nxt.costs
# method to calc. the no. of
# misplaced tiles, that is the no. of non-blank
# tiles not in their final posi
def calculateCosts(mats, final) -> int:
count = 0
for i in range(n):
for j in range(n):
if ((mats[i][j]) and
(mats[i][j] != final[i][j])):
count += 1
return count
def newNodes(mats, empty_tile_posi, new_empty_tile_posi,
levels, parent, final) -> nodes:
# Copying data from the parent matrixes to the present matrixes
new_mats = copy.deepcopy(mats)
# Moving the tile by 1 position
x1 = empty_tile_posi[0]
y1 = empty_tile_posi[1]
x2 = new_empty_tile_posi[0]
y2 = new_empty_tile_posi[1]
new_mats[x1][y1], new_mats[x2][y2] = new_mats[x2][y2], new_mats[x1][y1]
# Setting the no. of misplaced tiles
costs = calculateCosts(new_mats, final)
new_nodes = nodes(parent, new_mats, new_empty_tile_posi,
costs, levels)

17
return new_nodes
# func to print the N by N matrix
def printMatsrix(mats):
for i in range(n):
for j in range(n):
print("%d " % (mats[i][j]), end = " ")
print()
# func to know if (x, y) is a valid or invalid
# matrix coordinates
def isSafe(x, y):
return x >= 0 and x < n and y >= 0 and y < n
# Printing the path from the root node to the final node
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mats)
print()
# method for solving N*N - 1 puzzle algo
# by utilizing the Branch and Bound technique. empty_tile_posi is
# the blank tile position initially.
def solve(initial, empty_tile_posi, final):
# Creating a priority queue for storing the live
# nodes of the search tree
pq = priorityQueue()
# Creating the root node
costs = calculateCosts(initial, final)
root = nodes(None, initial,
empty_tile_posi, costs, 0)
# Adding root to the list of live nodes
pq.push(root)
# Discovering a live node with min. costs,
# and adding its children to the list of live
# nodes and finally deleting it from
# the list.
while not pq.empty():
# Finding a live node with min. estimated
# costs and deleting it form the list of the
# live nodes
minimum = pq.pop()
# If the min. is ans node
if minimum.costs == 0:
# Printing the path from the root to
# destination;

18
printPath(minimum)
return
# Generating all feasible children
for i in range(n):
new_tile_posi = [
minimum.empty_tile_posi[0] + rows[i],
minimum.empty_tile_posi[1] + cols[i], ]
if isSafe(new_tile_posi[0], new_tile_posi[1]):
# Creating a child node
child = newNodes(minimum.mats,
minimum.empty_tile_posi,
New_tile_posi,
minimum.levels + 1,
minimum, final,)
# Adding the child to the list of live nodes
pq.push(child)
# Main Code
# Initial configuration
# Value 0 is taken here as an empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
# Final configuration that can be solved
# Value 0 is taken as an empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
# Blank tile coordinates in the
# initial configuration
empty_tile_posi = [ 1, 2 ]
# Method call for solving the puzzle
solve(initial, empty_tile_posi, final)

19
OUTPUT:

RESULT:

Thus the program to solve the 8 Queens Problem has been successfully executed and
verified.

20
EX NO: 6 BREADTH FIRST SEARCH
DATE : 11/03/2023

AIM:

Write a program to solve any problem using Breadth First Search.

PROGRAM:

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')

Output:

ABCDEF

RESULT:
Thus the program to solve any problem using Breadth First Searchhas been
successfully executed and verified.

21
EX NO: 7 DEPTH FIRST SEARCH
DATE : 15/03/2023

AIM:

Write a program to solve any problem Depth FirstSearch

PROGRAM:

# Using a Python dictionary to act as an adjacency list


graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')

Output:
A
B
D
E
F
C

RESULT:
Thus the program to solve any problem Depth FirstSearch has been successfully
executed and verified.

22
EX NO:8 TRAVELLING SALESMAN PROBLEM
DATE : 29/03/2023

AIM:
To write a program to solve the Travelling Salesman Problem.

PROGRAM:
Prolog Program:
● DATASET:
edge(a, b, 3).
edge(a, c, 4).
edge(a, d, 2).
edge(a, e, 7).
edge(b, c, 4).
edge(b, d, 6).
edge(b, e, 3).
edge(c, d, 5).
edge(c, e, 8).
edge(d, e, 6).
edge(b, a, 3).
edge(c, a, 4).
edge(d, a, 2).
edge(e, a, 7).
edge(c, b, 4).
edge(d, b, 6).
edge(e, b, 3).
edge(d, c, 5).
edge(e, c, 8).
edge(e, d, 6).
edge(a, h, 2).
edge(h, d, 1).

● PROGRAM:
len([H|T], N):- len(T, X), N is X+1. best_path(Visited, Total):-path(a, a,
Visited,Total).
path(Start, Fin, Visited, Total):- path(Start, Fin, [Start], Visited, 0, Total).
path(Start, Fin, CurrentLoc, Visited, Costn, Total) :-edge(Start, StopLoc,
Distance), NewCostnis Costn + Distance, \+ member(StopLoc,

CurrentLoc),path(StopLoc,Fin,[StopLoc|CurrentLoc], Visited, NewCostn,Total).

23
path(Start, Fin, CurrentLoc, Visited, Costn, Total) :-edge(Start, Fin,Distance),
reverse([Fin|CurrentLoc], Visited), len(Visited, Q),(Q\=7 ->
Total is 100000; Total is Costn + Distance).shortest_path(Path):-setof(Cost-
Path, best_path(Path,Cost), Holder),pick(Holder,Path). best(Cost-
Holder,Bcost-_,Cost-Holder):- Cost<Bcost,!.best(_,X,X).
pick([Cost-Holder|R],X):- pick(R,Bcost-Bholder),best(Cost-Holder,Bcost-
Bholder,X),!.pick([X],X).

Python Program:
import numpy as np
from itertools import combinations
def TSP(G):n = len(G)
C = [[np.inf for _ in range(n)] for __ in range(1 << n)]C[1][0] = 0 # {0} <-> 1
for size in range(1, n):
for S in combinations(range(1, n), size):
S = (0,) + S
k = sum([1 << i for i in S])
for i in S:
if i == 0: continue
for j in S:
if j == i: continue
cur_index = k ^ (1 << i)
C[k][i] = min(C[k][i], C[cur_index][j]+ G[j][i])
#C[S−{i}][j]
all_index = (1 << n) - 1
return min([(C[all_index][i] + G[0][i], i) \
for i in range(n)])

OUTPUT:

RESULT:
Thus the program to solve the Travelling Salesman Problem has been successfully
executed and verified.

24
EX NO:9 WATER JUG PROBLEM
DATE : 01/04/2023

AIM
To write a program to solve the water jug problem

DESCRIPTION
Water Jug Problem: You are given two jugs, a 4lit one and a 3lit one, a pump which has
unlimited water which you can use to fill the jug, and the ground on which water may be
poured.Neither jug has any measuring markings on it. How can you get exactly 2lit of water in the
4lit jug?

Program:

start(2,0):-write(' 4lit Jug: 2 | 3lit Jug: 0|\n'),


write('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~\n'),write('Goal Reached!
Congrats!!\n'),
write('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~\n').
start(X,Y):-write(' 4lit Jug: '),write(X),write('| 3lit Jug: '),
write(Y),write('|\n'),
write(' Enter the
move::'),read(N),
contains(X,Y,N).
contains(_,Y,1):-start(4,Y).
contains(X,_,2):-start(X,3).
contains(_,Y,3):-start(0,Y).
contains(X,_,4):-start(X,0).
contains(X,Y,5):-N is Y-4+X, start(4,N).
contains(X,Y,6):-N is X-3+Y, start(N,3).
contains(X,Y,7):-N is X+Y, start(N,0).
contains(X,Y,8):-N is X+Y, start(0,N).
main():-write(' Water Jug
Game \n'), write('Intial
State: 4lit Jug- 0lit\n'),
write(' 3lit Jug- 0lit\n'),
write('Final State: 4lit
Jug- 2lit\n'), write(' 3lit
Jug- 0lit\n'),
write('Follow the
Rules: \n'), write('Rule
1: Fill 4lit Jug\n'),

25
write('Rule 2: Fill 3lit
Jug\n'), write('Rule 3:
Empty 4lit Jug\n'),
write('Rule 4: Empty
3lit Jug\n'),
write('Rule 5: Pour water from 3lit Jug to fill
4lit Jug\n'),write('Rule 6: Pour water from
4lit Jug to fill 3lit Jug\n'),write('Rule 7: Pour
all of water from 3lit Jug to 4lit Jug\n'),
write('Rule 8: Pour all of water from 4lit Jug
to 3lit Jug\n'), write(' 4lit Jug: 0 | 3lit Jug:
0'),nl,
write(' Enter the
move::'),
read(N),nl,
contains(0,0,N).

26
OUTPUT

PYTHON PROGRAM

from collections import deque


def Solution(a, b, target):
m = {}
isSolvable = False
path = []

q = deque()

#Initializing with jugs being empty


q.append((0, 0))

while (len(q) > 0):

# Current state

27
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("(", path[i][0], ",",
path[i][1], ")")
break

q.append([u[0], b]) # Fill Jug2


q.append([a, u[1]]) # Fill Jug1

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

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

28
if (not isSolvable):
print("Solution not possible")

if __name__ == '__main__':

Jug1, Jug2, target = 4, 3, 2


print("Path from initial state "
"to solution state ::")

Solution(Jug1, Jug2, target)

Output:

Path of states by jugs followed is :


0,0
0,3
3,0
3,3
4,2
0,2

RESULT

Thus, a program to solve the water jug problem was written and executed successfully
and the output is verified.

29
EX NO.10 MISSIONARIES AND CANNIBAL PROBLEM
DATE : 21/04/2023

AIM:
To write a program to solve missionaries and cannibal problem

PROCEDURE:

Question: In the missionaries and cannibals problem, three missionaries and three
cannibals must cross a river using a boat which can carry at most two people, under the
constraint that, for both banks, if there are missionaries present on the bank, they cannot be
outnumbered by cannibals (if they were, the cannibals would eat the missionaries). The boat
cannot cross the river by itself with no people on board.

Solution: First let us consider that both the missionaries (M) and cannibals(C) are on the same
side of the river. Left Right Initially the positions are : 0M , 0C and 3M , 3C (B) Now let’s send 2
Cannibals to left of bank : 0M , 2C (B) and 3M , 1C Send one cannibal from left to right : 0M , 1C
and 3M , 2C (B) Now send the 2 remaining Cannibals to left : 0M , 3C (B) and 3M , 0C Send 1
cannibal to the right : 0M , 2C and 3M , 1C (B) Now send 2 missionaries to the left : 2M , 2C (B)
and 1M . 1C Send 1 missionary and 1 cannibal to right : 1M , 1C and 2M , 2C (B) Send 2
missionaries to left : 3M , 1C (B) and 0M , 2C Send 1 cannibal to right : 3M , 0C and 0M , 3C (B)
Send 2 cannibals to left : 3M , 2C (B) and 0M , 1C Send 1 cannibal to right : 3M , 1C and 0M , 2C
(B)’ Send 2 cannibals to left : 3M , 3C (B) and 0M , 0C • Here (B) shows the position of the boat
after the action is performed. Therefore all the missionaries and cannibals have crossed the river
safely.

PYTHON PROGRAM

print("\n")
print("\tGame Start\nNow the task is to move all of them to right side of the river")
print("rules:\n1. The boat can carry at most two people\n2. If cannibals num greater than
missionaries then the cannibals would eat the missionaries\n3. The boat cannot cross the river
by itself with no people on board")
lM = 3 #lM = Left side Missionaries number
lC = 3 #lC = Laft side Cannibals number
rM=0 #rM = Right side Missionaries number
rC=0 #rC = Right side cannibals number
userM = 0
userC = 0
k=0
print("\nM M M C C C | --- | \n")
try:
while(True):
print("Left side -> right side river travel")

30
uM = int(input("Enter number of Missionaries travel => "))
uC = int(input("Enter number of Cannibals travel => "))
if((uM==0)and(uC==0)):
print("Empty travel not possible")
print("Re-enter : ")
elif(((uM+uC) <= 2)and((lM-uM)>=0)and((lC-uC)>=0)):
break
else:
print("Wrong input re-enter : ")

lM = (lM-uM)
lC = (lC-uC)
rM += uM
rC += uC
print("\n")

for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| --> | ",end="")
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")
k +=1

if(((lC==3)and (lM == 1))or((lC==3)and(lM==2))or((lC==2)and(lM==1))or((rC==3)and (rM ==


1))or((rC==3)and(rM==2))or((rC==2)and(rM==1))):
print("Cannibals eat missionaries:\nYou lost the game")
#break
if((rM+rC) == 6):
print("You won the game : \n\tCongrats")
print("Total attempt")
print(k)
#break
while(True):
print("Right side -> Left side river travel")
userM = int(input("Enter number of Missionaries travel => "))
userC = int(input("Enter number of Cannibals travel => "))
if((userM==0)and(userC==0)):
print("Empty travel not possible")
print("Re-enter : ")

31
elif(((userM+userC) <= 2)and((rM-userM)>=0)and((rC-userC)>=0)):
break
else:
print("Wrong input re-enter : ")
lM += userM
lC += userC
rM -= userM
rC -= userC
k +=1
print("\n")
for i in range(0,lM):
print("M ",end="")
for i in range(0,lC):
print("C ",end="")
print("| <-- | ",end="")
for i in range(0,rM):
print("M ",end="")
for i in range(0,rC):
print("C ",end="")
print("\n")

if(((lC==3)and (lM == 1))or((lC==3)and(lM==2))or((lC==2)and(lM==1))or((rC==3)and (rM ==


1))or((rC==3)and(rM==2))or((rC==2)and(rM==1))):
print("Cannibals eat missionaries:\nYou lost the game")
#break
except EOFError as e:
print("\nInvalid input please retry !!")

PROLOG PROGRAM

% Represent a state as [CL,ML,B,CR,MR]


start([3,3,left,0,0]).
goal([0,0,right,3,3]).
legal(CL,ML,CR,MR) :-
% is this state a legal one?
ML>=0, CL>=0, MR>=0, CR>=0,
(ML>=CL ; ML=0),
(MR>=CR ; MR=0).
% Possible moves:
move([CL,ML,left,CR,MR],[CL,ML2,right,CR,MR2]):-
% Two missionaries cross left to right.
MR2 is MR+2,
ML2 is ML-2,
legal(CL,ML2,CR,MR2).

32
move([CL,ML,left,CR,MR],[CL2,ML,right,CR2,MR]):-
CR2 is CR+2,
CL2 is CL-2,
legal(CL2,ML,CR2,MR).
move([CL,ML,left,CR,MR],[CL2,ML2,right,CR2,MR2]):-
% One missionary and one cannibal cross left to right.
CR2 is CR+1,
CL2 is CL-1,
MR2 is MR+1,
ML2 is ML-1,
legal(CL2,ML2,CR2,MR2).
move([CL,ML,left,CR,MR],[CL,ML2,right,CR,MR2]):-
% One missionary crosses left to right.
MR2 is MR+1,
ML2 is ML-1,
legal(CL,ML2,CR,MR2).
move([CL,ML,left,CR,MR],[CL2,ML,right,CR2,MR]):-
% One cannibal crosses left to right.
CR2 is CR+1,
CL2 is CL-1,
legal(CL2,ML,CR2,MR).
move([CL,ML,right,CR,MR],[CL,ML2,left,CR,MR2]):-
% Two missionaries cross right to left.
MR2 is MR-2,
ML2 is ML+2,
legal(CL,ML2,CR,MR2).
move([CL,ML,right,CR,MR],[CL2,ML,left,CR2,MR]):-
% Two cannibals cross right to left.
CR2 is CR-2,
CL2 is CL+2,
legal(CL2,ML,CR2,MR).
move([CL,ML,right,CR,MR],[CL2,ML2,left,CR2,MR2]):-
% One missionary and one cannibal cross right to left.
CR2 is CR-1,
CL2 is CL+1,
MR2 is MR-1,
ML2 is ML+1,
legal(CL2,ML2,CR2,MR2).
move([CL,ML,right,CR,MR],[CL,ML2,left,CR,MR2]):-
% One missionary crosses right to left.
MR2 is MR-1,
ML2 is ML+1,
legal(CL,ML2,CR,MR2).
move([CL,ML,right,CR,MR],[CL2,ML,left,CR2,MR]):-

33
% One cannibal crosses right to left.
CR2 is CR-1,
CL2 is CL+1,
legal(CL2,ML,CR2,MR).
% Recursive call to solve the problem
path([CL1,ML1,B1,CR1,MR1],[CL2,ML2,B2,CR2,MR2],Explored,MovesList) :-
move([CL1,ML1,B1,CR1,MR1],[CL3,ML3,B3,CR3,MR3]),
not(member([CL3,ML3,B3,CR3,MR3],Explored)),
path([CL3,ML3,B3,CR3,MR3],[CL2,ML2,B2,CR2,MR2],[[CL3,ML3,B3,CR3,MR3]|Explored],
[ [[CL3,ML3,B3,CR3,MR3],[CL1,ML1,B1,CR1,MR1]] | MovesList ]).
% Solution found
path([CL,ML,B,CR,MR],[CL,ML,B,CR,MR],_,MovesList):-
output(MovesList).
% Printing
output([]) :- nl.
output([[A,B]|MovesList]) :-
output(MovesList),
write(B), write(' -> '), write(A), nl.
% Find the solution for the missionaries and cannibals problem
find :-
path([3,3,left,0,0],[0,0,right,3,3],[[3,3,left,0,0]],_).

34
OUTPUT

RESULT

Thus, a program to solve missionaries and cannibal problems was written and executed
successfully and the output is verified.

35
EX NO :11 LIBRARY MANAGEMENT SYSTEM
DATE : 03/05/2023

AIM:

To write a Prolog program to simulate Library Management System.

PROGRAM:

% Define books with their properties


book(harry_potter_1, jk_rowling, 1997, fantasy).
book(harry_potter_2, jk_rowling, 1998, fantasy).
book(harry_potter_3, jk_rowling, 1999, fantasy).
book(the_hobbit, jrr_tolkien, 1937, fantasy).
book(the_lord_of_the_rings, jrr_tolkien, 1954, fantasy).
book(the_da_vinci_code, dan_brown, 2003, thriller).
book(angels_and_demons, dan_brown, 2000, thriller).
book(digital_fortress, dan_brown, 1998, thriller).
book(the_girl_with_the_dragon_tattoo, stieg_larsson, 2005, mystery).
book(the_girl_who_played_with_fire, stieg_larsson, 2006, mystery).
book(the_girl_who_kicked_the_hornets_nest, stieg_larsson, 2007, mystery).
% Define borrowers with their properties
borrower(john, doe, 12345).
borrower(jane, smith, 67890).
borrower(jack, black, 24680).
% Define the borrowed predicate
borrowed(harry_potter_1, 12345).
borrowed(the_hobbit, 67890).
borrowed(the_da_vinci_code, 24680).
borrowed(the_girl_with_the_dragon_tattoo, 12345).
borrowed(the_girl_who_played_with_fire, 67890).
% Define predicates for book search and borrower search
find_book_by_title(Title, Author, Year, Genre) :-
book(Title, Author, Year, Genre).
find_book_by_author(Author, Title, Year, Genre) :-
book(Title, Author, Year, Genre).
find_borrower_by_id(Id, FirstName, LastName) :-
borrower(FirstName, LastName, Id).
list_borrowed_books :-
borrowed(BookTitle, BorrowerId),

36
find_book_by_title(BookTitle, Author, Year, Genre),
find_borrower_by_id(BorrowerId, FirstName, LastName),
format('Book: ~w, Author: ~w, Year: ~w, Genre: ~w, Borrower: ~w ~w~n', [BookTitle, Author,
Year, Genre, FirstName, LastName]).

OUTPUT:

RESULT:

Thus, the prolog program to simulate a library management system has been executed
successfully.

37

You might also like