Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

AI AND APPLICATION LAB

(18B17CI475)

LAB RECORD

Submitted by
ARPIT AWASTHI [221B086]

Submitted to: Dr. Amit Kumar

2023-2024

Department of Computer Science & Engineering


JAYPEE UNIVERSITY OF ENGINEERING &
TECHNOLOGY, AB ROAD, RAGHOGARH,
DT. GUNA-473226 MP, INDIA

INDEX
Exp. ExperimentTitleStart End Signatur
No. Date Date e

Problem 1: Solve “Tower of Hanoi” with only 2 disks and then 3


disks. def tower_of_hanoi(n,source,target,auxiliary):
if n==1:
print("Move disk 1 from {} to {}".format(source,target))
return
tower_of_hanoi(n-1,source,auxiliary,target)
print("Move disk {} from {} to {}".format(n,source,target))
tower_of_hanoi(n-1,auxiliary,target,source)

print("Tower of Hanoi with 2 disks:")


tower_of_hanoi(2,'A','C','B')
print("\nTower of Hanoi with 3 disks:")
tower_of_hanoi(3,'A','C','B')

Problem 2: Solve “4-Queens” and “8-Queens” puzzle.


def is_safe(board,row,col):
for i in range(col):
if board[row][i]:
return False
for i,j in zip(range(row,-1,-1),range(col,-1,-1)):
if board[i][j]:
return False
for i,j in zip(range(row,N,1),range(col,-1,-1)):
if board[i][j]:
return False
return True

def solve_queens_util(board,col):
if col>=N:
return True
for i in range(N):
if is_safe(board,i,col):
board[i][col]=1
if solve_queens_util(board,col+1):
return True

board[i][col]=0
return False

def solve_queens(n):
global N
N=n
board=[[0 for _ in range(N)]for _ in range(N)]
if not solve_queens_util(board,0):

print("Solution does not exist")


return False
print_board(board)
return True

def print_board(board):
for i in range(N):
for j in range(N):
print(board[i][j],end=" ")
print()

if __name__=="__main__":
solve_queens(4)
print("\n")
solve_queens(8)

Problem 3: Solve “4-color map” problem.


class MapColoring:
def __init__(self,graph):
self.graph=graph
self.num_nodes=len(graph)
self.colors=[0]*self.num_nodes

def is_safe(self,node,color):
for neighbor in self.graph[node]:
if self.colors[neighbor]==color:
return False
return True

def solve(self,node):
if node==self.num_nodes:
return True
for color in range(1,5):
if self.is_safe(node,color):
self.colors[node]=color if
self.solve(node+1): return True
self.colors[node]=0 return
False

def color_map(self):
if self.solve(0):
color_map={}
for i in range(self.num_nodes):
color_map[i]=self.colors[i] return
color_map

else:
return "No solution exists."

if __name__=="__main__":
graph={
0:[1,2,3],
1:[0,2],
2:[0,1,3],
3:[0,2]
}
map_coloring=MapColoring(graph)
result=map_coloring.color_map()
print("Coloring of the map:")
print(result)

Problem 4: Solve “8 – puzzle” and “15-puzzle” take any initial and


goal state.
import heapq
class PuzzleNode:
def __init__(self,state,parent=None,action=None,cost=0):
self.state=state
self.parent=parent
self.action=action
self.cost=cost
if self.parent:
self.depth=parent.depth+1
else:
self.depth=0

def __lt__(self,other):
return(self.cost+self.depth)<(other.cost+other.depth)

def __eq__(self,other):
return self.state==other.state
def __hash__(self):
return hash(str(self.state))

def expand(self):
children=[]
for action in self.actions():
next_state=self.result(action)
if next_state:
children.append(PuzzleNode(next_state,self,action,self.cost+1)) return
children

def actions(self):
actions=[]
i,j=self.find_blank()
if i>0:
actions.append('up')
if i<2:
actions.append('down')
if j>0:
actions.append('left')
if j<2:
actions.append('right')
return actions
def result(self, action):
i,j=self.find_blank()
new_state=[row[:] for row in self.state]
if action=='up':
new_state[i][j],new_state[i-1][j]=new_state[i-1][j],new_state[i][j] elif
action=='down':

new_state[i][j],new_state[i+1][j]=new_state[i+1][j],new_state[i][j] elif
action=='left':

new_state[i][j], new_state[i][j-1]=new_state[i][j-1],new_state[i][j] elif


action=='right':

new_state[i][j],new_state[i][j+1]=new_state[i][j+1],new_state[i][j] else:
return None

return new_state

def find_blank(self):
for i in range(3):
for j in range(3):
if self.state[i][j]==0:
return i,j
return None

def print_path(self):
path=[]
node=self
while node:
path.append(node.state)
node=node.parent
path.reverse()
for state in path:
print_state(state)
print()

def print_state(state):
for row in state:
print(row)
print()

def manhattan_distance(state):
distance=0
for i in range(3):
for j in range(3):
if state[i][j]!=0:
x,y=divmod(state[i][j]-1,3)
distance+=abs(x-i)+abs(y-j) return
distance

def solve_puzzle(initial_state):
initial_node=PuzzleNode(initial_state)
frontier=[initial_node]

visited=set()
heapq.heapify(frontier)
while frontier:
node=heapq.heappop(frontier) if
node.state==goal_state:
return node
visited.add(node)
for child in node.expand(): if
child not in visited:
heapq.heappush(frontier,child) return
None

initial_state=[[1,2,3],
[4,5,6],
[7,8,0]]
goal_state=[[1,2,3],
[4,5,6],
[7,8,0]]
solution_node=solve_puzzle(initial_state
) if solution_node:

print("Solution found:")
solution_node.print_path()
else:
print("No solution found.")
Problem 5: Solve “Latin Square” problem.
def is_safe(square,row,col,num):
if num in square[row]:
return False
for i in range(len(square)):
if square[i][col]==num:
return False
return True

def
solve_latin_square(square,n,row=0,col=0): if
row==n:

return True
if col==n:
return solve_latin_square(square,n,row+1,0) if
square[row][col]!=0:

return solve_latin_square(square,n,row,col+1) for


num in range(1,n+1):

if is_safe(square,row,col,num):
square[row][col]=num
if solve_latin_square(square,n,row,col+1):
return True

square[row][col]=0
return False

def print_square(square):
for row in square:
print(" ".join(map(str,row)))
def latin_square(n):
square=[[0]*n for _ in range(n)]
if solve_latin_square(square,n):
print("Latin Square Solution:")
print_square(square)
else:
print("No solution exists for the given size.")

n=4
latin_square(n)

Problem 6: Code the game: Tick-Tac-Toe.


def print_board(board):
for row in board:
print(" | ".join(row))
print("-"*5)

def check_winner(board):
for row in board:
if row[0]==row[1]==row[2]!=' ':
return row[0]
for col in range(3):
if board[0][col]==board[1][col]==board[2][col]!=' ':
return board[0][col]
if board[0][0]==board[1][1]==board[2][2]!=' ':
return board[0][0]

if board[0][2]==board[1][1]==board[2][0]!=' ':
return board[0][2]

return None

def tic_tac_toe():
board=[[' ' for _ in range(3)]for _ in range(3)]
player='X'

while True:
print_board(board)
row=int(input("Enter row (0,1,or 2): "))
col=int(input("Enter column (0,1,or 2): ")) if
board[row][col]==' ':

board[row][col]=player
winner=check_winner(board)
if winner:
print_board(board)
print(f"Player {winner} wins!")
break
elif all(all(cell!=' ' for cell in row)for row in board):
print_board(board)

print("It's a draw!")
break
else:
player='O' if player=='X' else 'X' else:
print("That cell is already occupied. Try again.")

if __name__=="__main__":
tic_tac_toe()

Problem 7: Code the game: Checkers.


class Checkers:
def __init__(self):
self.board = [
[" ","X"," ","X"," ","X"," ","X"],
["X"," ","X"," ","X"," ","X"," "],
[" ","X"," ","X"," ","X"," ","X"],
[" "," "," "," "," "," "," "," "],
[" "," "," "," "," "," "," "," "],
["O"," ","O"," ","O"," ","O"," "],
[" ","O"," ","O"," ","O"," ","O"],
["O"," ","O"," ","O"," ","O"," "]
]
self.current_player="X"

def print_board(self):
for row in self.board:
print(" | ".join(row))
print("-"*29)
def is_valid_move(self,start,end):
x1,y1=start
x2,y2=end
if self.board[x2][y2]!=" ":
return False
if self.board[x1][y1]=="X":
if x2-x1==1 and abs(y2-y1)==1:
return True
elif x2-x1==2 and abs(y2-y1)==2: if
self.board[(x1+x2)//2][(y1+y2)//2]=="O": return
True

elif self.board[x1][y1]=="O":
if x1-x2==1 and abs(y2-y1)==1:
return True
elif x1-x2==2 and abs(y2-y1)==2: if
self.board[(x1+x2)//2][(y1+y2)//2]=="X": return
True

return False
def make_move(self,start,end):
x1,y1=start
x2,y2=end
self.board[x2][y2]=self.board[x1][y1]
self.board[x1][y1]=" "
if abs(x2-x1)==2:
self.board[(x1+x2)//2][(y1+y2)//2]=" "

def switch_player(self):
self.current_player="O" if self.current_player=="X" else "X"

def play(self):
while True:
self.print_board()
print(f"Player {self.current_player}'s turn")
start=tuple(map(int, input("Enter start position (row, column): ").split(",")))
end=tuple(map(int, input("Enter end position (row, column): ").split(","))) if
self.is_valid_move(start,end):

self.make_move(start,end)
self.switch_player()
else:
print("Invalid move, try again.")
if self.check_winner():
print(f"Player {self.current_player} wins!")
break

def check_winner(self):
for row in self.board:
if "X" in row and "O" not in row:
return True
if "O" in row and "X" not in row:
return True

return False

if __name__ == "__main__":
game=Checkers()
game.play()

You might also like