Practical 2
Practical 2
2024-2025 Practical-2
Practical-2
AIM: Write a python program to solve a Water Jug Problem by using Breadth first search (BFS).
Program should be written in generalized way to solve by using any capacity of jug.
Create Class Node, bfs_algo, water_jug with appropriate method and variables.
Find the minimum number of steps to reach the goal states entered by user.
Check evaluating criteria Completeness, Optimality, execution time, No. of explored Nodes of BFS
algorithm. (Only “time” packages can be used in python if it is necessary to use)
Example:A Water Jug Problem: You are given two jugs, a 4-gallon one and a 3-gallon 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 2 gallons of water in the 4-gallon jug?
Reach any of the Goal states: (X=2, Y=0), (X=2, Y=1), (X=2, Y=2), (X=2, Y=3)
CODE:
import time
class node:
self.x = 0
self.y = 0
self.parent = data
x = cnode.x
y = cnode.y
if rule == 1:
if x < maxjug1:
x = maxjug1
else:
return None
elif rule == 2:
if y < maxjug2:
y = maxjug2
else:
return None
elif rule == 3:
if x > 0:
x=0
else:
return None
elif rule == 4:
if y > 0:
Name: Krishna Chitlangia
Enrollment No: 22012011016
Batch: 6CE-D-2 Page | 2
Artificial Intelligence A.Y. 2024-2025 Practical-2
y=0
else:
return None
elif rule == 5:
if x + y >= maxjug1:
y = y - (maxjug1 - x)
x = maxjug1
else:
return None
elif rule == 6:
if x + y >= maxjug2:
x = x - (maxjug2 - y)
y = maxjug2
else:
return None
elif rule == 7:
if x + y < maxjug1:
x=x+y
y=0
else:
return None
elif rule == 8:
if x + y < maxjug2:
y=x+y
x=0
else:
return None
Name: Krishna Chitlangia
Enrollment No: 22012011016
Batch: 6CE-D-2 Page | 3
Artificial Intelligence A.Y. 2024-2025 Practical-2
return None
nextnode = node(cnode)
nextnode.x = x
nextnode.y = y
nextnode.parent = cnode
return nextnode
class searchBFS:
self.queue = []
def popnode(self):
return self.queue.pop(0)
def search(self):
self.queue.append(initialNode)
while len(self.queue) != 0:
cnode = self.popnode()
return cnode
l = self.generateAllSuccessors(cnode)
self.queue.extend(l)
return None
list1 = []
if nextnode != None:
list1.append(nextnode)
return list1
temp = cnode
list1 = []
list1.append(temp)
temp = temp.parent
list1.reverse()
for i in list1:
self.printnode(i)
initialNode = node(None)
initialNode.x = 0
initialNode.y = 0
initialNode.parent = None
goalNode = node(None)
goalNode.y = 0
goalNode.parent = None
start_time = time.time()
solutionNode = solution.search()
end_time = time.time()
if solutionNode != None:
solution.printPath(solutionNode)
else:
OUTPUT: