AI Lab Programs
AI Lab Programs
# Fill Jug 1
if dfs(5, y, "Fill Jug 1", target, visited, path):
return True
# Fill Jug 2
if dfs(x, 3, "Fill Jug 2", target, visited, path):
return True
# Empty Jug 1
if dfs(0, y, "Empty Jug 1", target, visited, path):
return True
# Empty Jug 2
if dfs(x, 0, "Empty Jug 2", target, visited, path):
return True
# Backtrack
path.pop()
return False
def solve(target):
visited = set()
path = []
if dfs(0, 0, "Start", target, visited, path):
print("\nSolution path:")
for a, b, act in path:
print(f"Jug1: {a}, Jug2: {b} -> {act}")
else:
print("No solution found.")
# Example run
if __name__ == "__main__":
try:
target = int(input("Enter the target amount of water: "))
if 0 < target <= 5:
solve(target)
else:
print("Target must be between 1 and 5 (inclusive) for the 5L-3L jug
problem.")
except ValueError:
print("Please enter a valid integer.")
2. Implement and Demonstrate Best First Search Algorithm on
Missionaries-Cannibals Problems using Python.
from collections import deque
def is_valid(state):
ml, cl, boat, mr, cr, _ = state
def next_states(state):
ml, cl, boat, mr, cr, _ = state
moves = [
(0, 2, "2C"),
(0, 1, "1C"),
(1, 0, "1M"),
(2, 0, "2M"),
(1, 1, "1M and 1C"),
]
next_states = []
for m, c, action in moves:
if boat == 1: # Boat on right bank, move to left
new_state = (ml + m, cl + c, 0, mr - m, cr - c, f"Move {action} to left")
else: # Boat on left bank, move to right
new_state = (ml - m, cl - c, 1, mr + m, cr + c, f"Move {action} to right")
if is_valid(new_state):
next_states.append(new_state)
return next_states
def solve():
start_state = (0, 0, 1, 3, 3, "Start: 3M and 3C on right bank")
goal_state = (3, 3, 0, 0, 0) # All on left bank, boat on left
while queue:
current_state, path = queue.popleft()
ml, cl, boat, mr, cr, _ = current_state
return None
while open_list:
_, current = heapq.heappop(open_list)
# Explore neighbors
for neighbor, cost in enumerate(graph[current]):
if cost == 0:
continue # Skip if not connected
# No path found
return None, float('inf')
graph = [
[0, 1, 4, 0, 0, 0],
[1, 0, 2, 5, 0, 0],
[4, 2, 0, 3, 6, 0],
[0, 5, 3, 0, 2, 7],
[0, 0, 6, 2, 0, 4],
[0, 0, 0, 7, 4, 0]
]
heuristic = {
0: 10,
1: 8,
2: 6,
3: 4,
4: 2,
5: 0
}
start_node = 0
goal_node = 5
if path:
print("Path:", path)
print("Total Cost:", total_cost)
else:
print("No path found.")
def ao_star(start):
solved = set()
frontier = [(start, start.heuristic)]
total_cost = 0
while frontier:
node, _ = frontier.pop(0)
if not node.children:
solved.add(node)
continue
total_cost = min_cost
solved.add(node)
return solved, total_cost
A = Node('A', 10)
B = Node('B', 8)
C = Node('C', 6)
D = Node('D', 4)
E = Node('E', 2)
F = Node('F', 1)
G = Node('G', 0)
if row == 8:
solutions.append(position[:]) # Found a valid solution
return
return solutions
path = [start]
current = start
while unvisited:
# Choose the closest unvisited city
next_city = min(unvisited, key=lambda city: graph[current][city])
path.append(next_city)
unvisited.remove(next_city)
current = next_city
return path
start = 0
path = travel(graph, start)
# Check each rule: if the antecedent is already known, we can add the
consequent
for antecedent, consequent in rules:
if antecedent in known and consequent not in known:
known.add(consequent)
added_new_fact = True
print(f"Inferred '{consequent}' because '{antecedent}' is known.")
return known
# Backward -Chaining
# Rules are expressed as: if antecedent then consequent
print('\nBackward Chaining:')
facts = [
['croaks', 'frog'],
['eats flies', 'frog'],
['frog', 'green'],
['chirps', 'canary'],
['sings', 'canary'],
['canary', 'yellow']
]
for g in goals:
result = backward_chain(facts, g, known_facts.copy())
print(f"Can we prove '{g}'? ->", "Yes" if result else "No")
# Output:
# Can we prove 'frog'? → Yes
# Can we prove 'green'? → Yes
# Can we prove 'canary'? → No
# Can we prove 'yellow'? → No
7. Implement resolution principle on FOPL related problems.
import re
# Sample formula
formula = "A and B or C or D"
# Run transformations
print("Original:", formula)
print("CNF:", to_cnf(formula))
print("DNF:", to_dnf(formula))
8. Implement any Game and demonstrate the Game playing strategies.
import random
class TicTacToe:
def __init__(self):
self.board = [' '] * 9 # 3x3 board flattened
def display(self):
# Print board in 3 rows
for i in range(0, 9, 3):
print(f" {self.board[i]} | {self.board[i+1]} | {self.board[i+2]} ")
if i < 6: print("---+---+---")
def available_moves(self):
# List empty positions
return [i for i, val in enumerate(self.board) if val == ' ']
def is_full(self):
# Board full if no empty spots
return ' ' not in self.board
def game_over(self):
# Check if either player won or board full
return self.is_winner('X') or self.is_winner('O') or self.is_full()
# Base cases
if game.is_winner('X'): return {'score': 1}
if game.is_winner('O'): return {'score': -1}
if game.is_full(): return {'score': 0}
moves = []
for move in game.available_moves():
new_game = TicTacToe()
new_game.board = game.board[:] # copy board
new_game.make_move(move, player)
def play_game():
game = TicTacToe()
current = 'X' # X uses minimax, O moves randomly
print("Starting Tic-Tac-Toe:")
game.display()
game.make_move(move, current)
game.display()
if game.is_winner(current):
print(f"\n{current} wins!")
return
elif game.is_full():
print("\nIt's a draw!")
return
# Switch player
current = 'O' if current == 'X' else 'X'
if __name__ == "__main__":
play_game()