Practical - 4: CS341 Artificial Intelligence Lab Manual
Practical - 4: CS341 Artificial Intelligence Lab Manual
Practical – 4
Aim: Solve Water Jug problem using BFS and DFS search techniques.
Program –
#To be noted that both search techniques are implemented in the same code.
import collections
"""
Branching Factor: 6 (because we have 6 operators)
"""
def main():
"""
main function
"""
def get_index(node):
"""
returns a key value for a given node
def get_search_type():
"""
Returns True for DFS, False otherwise.
"""
return s == 'd'
def get_jugs():
"""
Returns a list of two integeres representing volumes of the jugs.
Takes volumes of the jugs as an input from the user.
"""
print("Receiving the volume of the jugs...")
jugs = []
return jugs
def get_goal(jugs):
"""
Returns desired amount of water.
Takes desired amount as an input from the user.
return goal_amount
result = []
next_nodes = []
node = []
a_max = jugs[0]
b_max = jugs[1]
next_nodes.append(node)
node = []
#if len(next_nodes) == 0:
# print("No more unvisited nodes...\nBacktracking...")
#else:
#print("Possible transitions: ")
#for nnode in next_nodes:
# print(nnode)
return result
"""
returns a string explaining the transition from old state/node to new state/node
a = old[0]
b = old[1]
a_prime = new[0]
b_prime = new[1]
a_max = jugs[0]
b_max = jugs[1]
if a > a_prime:
if b == b_prime:
return "Clear {0}-liter jug:\t\t\t".format(a_max)
else:
return "Pour {0}-liter jug into {1}-liter jug:\t".format(a_max, b_max)
else:
if b > b_prime:
if a == a_prime:
return "Clear {0}-liter jug:\t\t\t".format(b_max)
else:
return "Pour {0}-liter jug into {1}-liter jug:\t".format(b_max, a_max)
else:
if a == a_prime:
return "Fill {0}-liter jug:\t\t\t".format(b_max)
else:
return "Fill {0}-liter jug:\t\t\t".format(a_max)
starting_node: a list of list of two integers representing initial state of the jugs
jugs: a list of two integers representing volumes of the jugs
goal_amount: an integer represting the desired amount
check_dict: a dictionary storing visited nodes
is_depth: implements DFS, if True; BFS otherwise
"""
if is_depth:
print("Implementing DFS...")
else:
print("Implementing BFS...")
goal = []
accomplished = False
q = collections.deque()
q.appendleft(starting_node)
while len(q) != 0:
path = q.popleft()
check_dict[get_index(path[-1])] = True
if len(path) >= 2:
print(transition(path[-2], path[-1], jugs), path[-1])
if is_goal(path, goal_amount):
accomplished = True
goal = path
break
else:
q.append(i)
if accomplished:
print("The goal is achieved\nPrinting the sequence of the moves...\n")
print_path(goal, jugs)
else:
print("Problem cannot be solved.")
if __name__ == '__main__':
print("Mann Patel,18DCS074.")
main()
Screenshot:
BFS:
DFS:
Conclusion:
In this practical we learnt to solve the Water Jug problem using Breadth first
search technique and Depth first search technique.