Ai2913 9
Ai2913 9
display([]).
display([X|T]):-
write(X),nl/0,
display([T]).
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_length([],0).
list_length([_|TAIL],N) :- list_length(TAIL,N1), N is N1 + 1.
last_element([X], X).
last_element([_|T], X) :-
last_element(T, X).
list_sum([],0).
list_sum([Head|Tail], TotalSum):-
list_sum(Tail, Sum1),
TotalSum is Head+Sum1.
92100103291 4
Screenshot:
92100103291 5
Practical 4: Implement a Family Tree and define the following predicates:
parent(X,Y)
Father(X,Y)
Mother(X,Y)
Sister(X,Y)
Brother(X,Y)
Grandfather(X,Y)
Grandmother(X,Y)
male(jack).
male(oliver).
male(ali).
male(james).
male(simon).
male(harry).
female(helen).
female(sophie).
female(jess).
female(lily).
parent_of(jack,jess).
parent_of(jack,lily).
parent_of(helen,jess).
parent_of(helen,lily).
parent_of(oliver,james).
parent_of(sophie,james).
parent_of(jess,simon).
parent_of(ali,simon).
parent_of(lily,harry).
parent_of(james,harry).
father_of(X,Y):-male(X),parent_of(X,Y).
mother_of(X,Y):-female(X),parent_of(X,Y).
grandfather_of(X,Y):-male(X),parent_of(X,Z),parent_of(Z,Y).
grandmother_of(X,Y):-female(X),parent_of(X,Z),parent_of(Z,Y).
sister_of(X,Y):-female(X),father_of(F,Y),father_of(F,X),X\=Y.
sister_of(X,Y):-female(X),mother_of(M,Y),mother_of(M,X),X\=Y.
brother_of(X,Y):-male(X),father_of(F,Y),father_of(F,X),X\=Y.
brother_of(X,Y):-male(X),mother_of(M,Y),mother_of(M,X),X\=Y.
Screenshot:
92100103291 6
92100103291 7
Practical 5: Assume given a set of facts of the form father(name1,name2) (name1 is
the father of name2)
Define a predicate cousin(X,Y) which holds iff 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. Define a
predicate grandparent(X,Y) which holds iff X is a grandparent 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:
?- cousin(X,Y).
?- grandson(X,Y).
?- descendent(X,Y).
?-grandparent(X,Y).
father(a,b).
father(a,c).
father(b,d).
father(b,e).
father(c,f).
brother(X,Y) :-
father(Z,X), father(Z,Y), not(X=Y).
cousin(X,Y) :-
father(Z,X), father(W,Y), brother(Z,W).
grandson(X,Y) :-
father(Z,X), father(Y,Z).
descendent(X,Y) :-
father(Y,X).
descendent(X,Y) :-
father(Z,X), descendent(Z,Y).
grandfather(X,Y):-
grandson(Y,X).
92100103291 8
Screenshot:
92100103291 9
Practical 6: Write a program to solve the Tower of Hanoi problem.
move(1,X,Y,_) :-
write('Move top disk from '),
write(X), write('to '), write(Y), nl.
move(N,X,Y,Z) :-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).
Screenshot:
92100103291 10
Practical 7: Write a program to implement BFS for the Water Jug problem.
from collections import deque
def BFS(a, b, target):
m = {}
isSolvable = False
path = []
q = deque()
q.append((0, 0))
while (len(q) > 0):
u = q.popleft()# If this state is already visited
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
# Filling the vector for constructing
# the solution path
path.append([u[0], u[1]])
if (u[0] == target):
if (u[1] != 0):
# Fill final state
path.append([u[0], 0])
else:
if (u[0] != 0):
# Fill final state
path.append([0, u[1]])
Screenshot:
92100103291 12
Practical 8: Write a program to implement DFS for the Water Jug problem.
def is_goal(state, target):
return target in state
# Fill Jug1
if jug1 < max1:
successors.append((max1, jug2))
# Fill Jug2
if jug2 < max2:
successors.append((jug1, max2))
# Empty Jug1
if jug1 > 0:
successors.append((0, jug2))
# Empty Jug2
if jug2 > 0:
successors.append((jug1, 0))
# Pour Jug1 to Jug2
if jug1 > 0 and jug2 < max2:
pour_amount = min(jug1, max2 - jug2)
successors.append((jug1 - pour_amount, jug2 + pour_amount))
# Pour Jug2 to Jug1
if jug2 > 0 and jug1 < max1:
pour_amount = min(jug2, max1 - jug1)
successors.append((jug1 + pour_amount, jug2 - pour_amount))
return successors
while stack:
state = stack.pop()
if state in visited:
continue
visited.add(state)
if is_goal(state, target):
path = []
while state:
path.append(state)
92100103291 13
state = parent_map.get(state)
return path[::-1]
return None
# Example usage
start_state = (0, 0) # Both jugs are empty initially
jug_capacities = (4, 3) # Capacity of jug1 is 4 liters, jug2 is 3 liters
target = 2 # The goal is to measure exactly 2 liters
Screenshot:
92100103291 14
Practical 9: Write a program to implement Single Player Game (Using Heuristic
Function).
import heapq
class PuzzleState:
def __init__(self, board, moves=0, previous=None):
self.board = board
self.moves = moves
self.previous = previous
self.blank_pos = self.find_blank()
def find_blank(self):
for i in range(3):
for j in range(3):
if self.board[i][j] == 0:
return (i, j)
raise ValueError("Blank space (0) not found in the board.")
def priority(self):
return self.moves + self.manhattan_distance()
def manhattan_distance(self):
distance = 0
for i in range(3):
for j in range(3):
if self.board[i][j] != 0:
x, y = divmod(self.board[i][j] - 1, 3)
distance += abs(x - i) + abs(y - j)
return distance
def is_goal(self):
goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
return self.board == goal
def generate_successors(self):
successors = []
x, y = self.blank_pos
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:
new_board = [row[:] for row in self.board]
new_board[x][y], new_board[new_x][new_y] = new_board[new_x][new_y], new_board[x][y]
successors.append(PuzzleState(new_board, self.moves + 1, self))
return successors
92100103291 15
def print_board(board):
for row in board:
print(" ".join(str(num) if num != 0 else "_" for num in row))
print()
def a_star_search(initial_board):
start_state = PuzzleState(initial_board)
open_set = []
heapq.heappush(open_set, start_state)
closed_set = set()
while open_set:
current_state = heapq.heappop(open_set)
if current_state.is_goal():
return current_state
closed_set.add(tuple(map(tuple, current_state.board)))
return None
def reconstruct_path(state):
path = []
while state:
path.append(state.board)
state = state.previous
return path[::-1]
def main():
print("Md Aman- 92100103291\n")
print("Enter the initial state of the 8-puzzle, using 0 for the blank space:")
initial_board = []
for _ in range(3):
row = list(map(int, input().split()))
initial_board.append(row)
print("\nInitial board:")
print_board(initial_board)
solution = a_star_search(initial_board)
92100103291 16
if solution:
path = reconstruct_path(solution)
print(f"\nSolved in {len(path) - 1} moves.\n")
for i, step in enumerate(path):
print(f"Step {i}:")
print_board(step)
else:
print("No solution found.")
if __name__ == "__main__":
main()
Screenshot:
92100103291 17