0% found this document useful (0 votes)
13 views14 pages

Ai2913 9

Uploaded by

Md Aman
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)
13 views14 pages

Ai2913 9

Uploaded by

Md Aman
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/ 14

Practical 3: Write a Prolog program to perform the following operations of the list:

i) To display the element of the given list.


ii) To check if a given element is in the list or not.
iii) To print the last element of the list.
iv) To print the sum of the elements of the given list.

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

# Marking current state as visited


m[(u[0], u[1])] = 1

# If we reach solution state, put ans=1


if (u[0] == target or u[1] == target):
isSolvable = True

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

# Print the solution path


sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break
# If we have not reached final state
# then, start developing intermediate
# states to reach solution state
q.append([u[0], b]) # Fill Jug2
q.append([a, u[1]]) # Fill Jug1
92100103291 11
for ap in range(max(a, b) + 1):
# Pour amount ap from Jug2 to Jug1
c = u[0] + ap
d = u[1] - ap
# Check if this state is possible or not
if (c == a or (d == 0 and d >= 0)):
q.append([c, d])
# Pour amount ap from Jug 1 to Jug2
c = u[0] - ap
d = u[1] + ap
# Check if this state is possible or not
if ((c == 0 and c >= 0) or d == b):
q.append([c, d])
# Empty Jug2
q.append([a, 0])
# Empty Jug1
q.append([0, b])
# No, solution exists if ans=0
if (not isSolvable):
print("No solution")
# Driver code
if __name__ == '__main__':
Jug1, Jug2, target = 4, 3, 2
print("Md Aman 92100103291\nPath from initial state to solution state ::")
BFS(Jug1, Jug2, target)

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

def get_successors(state, capacities):


successors = []
jug1, jug2 = state
max1, max2 = capacities

# 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

def dfs_water_jug(start, capacities, target):


stack = [start]
visited = set()
parent_map = {}

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]

for successor in get_successors(state, capacities):


if successor not in visited:
stack.append(successor)
parent_map[successor] = state

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

solution_path = dfs_water_jug(start_state, jug_capacities, target)


print("Md Aman 92100103291")
if solution_path:
print("Solution path found:")
for state in solution_path:
print(state)
else:
print("No solution found.")

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 __lt__(self, other):


return self.priority() < other.priority()

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

for successor in current_state.generate_successors():


state_tuple = tuple(map(tuple, successor.board))
if state_tuple not in closed_set:
heapq.heappush(open_set, successor)
closed_set.add(state_tuple)

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy