0% found this document useful (0 votes)
22 views27 pages

Aies Lab Dharani

AIES LAB(PROGRAM)
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)
22 views27 pages

Aies Lab Dharani

AIES LAB(PROGRAM)
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/ 27

PROGRAM

global N
N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()

def isSafe(board, row, col):


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

def solveNQUtil(board, col):


if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col + 1) == True:
return True
board[i][col] = 0
return False

def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]

if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True

solveNQ()

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
0010
1000
0001
0100

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
from collections import defaultdict

class Graph:
def init (self):
self.graph = defaultdict(list)

def addEdge(self,u,v):
self.graph[u].append(v)

def DFSUtil(self, v, visited):


visited[v]= True
print (v)
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)

def DFS(self):
V = len(self.graph)
visited =[False]*(V)
for i in range(V):
if visited[i] == False:
self.DFSUtil(i, visited)

g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Following is Depth First Traversal")
g.DFS()

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
Following is Depth First Traversal
0
1
2
3

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
from queue import PriorityQueue
v = 14
graph = [[] for i in range(v)]

def best_first_search(actual_Src, target, n):


visited = [False] * n
pq = PriorityQueue()
pq.put((0, actual_Src))
visited[actual_Src] = True
while pq.empty() == False:
u = pq.get()[1]
print(u, end=" ")
if u == target:
break
for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print()

def addedge(x, y, cost):


graph[x].append((y, cost))
graph[y].append((x, cost))

addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(0, 3, 5)
addedge(1, 4, 9)
addedge(1, 5, 8)
addedge(2, 6, 12)
addedge(2, 7, 14)
addedge(3, 8, 7)
REG NO: 211423243098 NAME:DHARANIDHARAN S
addedge(8, 9, 5)
addedge(8, 10, 6)
addedge(9, 11, 1)
addedge(9, 12, 10)
addedge(9, 13, 2)
source = 0
target = 9
best_first_search(source, target, v)

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
013289

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
def TowerOfHanoi(n , source, destination, auxiliary):
if n==1:
print ("Move disk 1 from source",source,"to destination",destination)
return
TowerOfHanoi(n-1, source, auxiliary, destination)
print ("Move disk",n,"from source",source,"to destination",destination)
TowerOfHanoi(n-1, auxiliary, destination, source)
n=4
TowerOfHanoi(n,'A','B','C')

OUTPUT
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B
Move disk 3 from source A to destination C
Move disk 1 from source B to destination A
Move disk 2 from source B to destination C
Move disk 1 from source A to destination C
Move disk 4 from source A to destination B
Move disk 1 from source C to destination B
Move disk 2 from source C to destination A
Move disk 1 from source B to destination A
Move disk 3 from source C to destination B
Move disk 1 from source A to destination C
Move disk 2 from source A to destination B
Move disk 1 from source C to destination B

REG NO: 211423243098 NAME:DHARANIDHARAN S


REG NO: 211423243098
REG
PROGRAM
from collections import defaultdict
jug1, jug2, aim = 4, 3, 2
visited = defaultdict(lambda: False)

def waterJugSolver(amt1, amt2):


if (amt1 == aim and amt2 == 0) or (amt2 == aim and amt1 == 0):
print(amt1, amt2)
return True
if visited[(amt1, amt2)] == False:
print(amt1, amt2)
visited[(amt1, amt2)] = True
return (waterJugSolver(0, amt2) or
waterJugSolver(amt1, 0) or
waterJugSolver(jug1, amt2) or
waterJugSolver(amt1, jug2) or
waterJugSolver(amt1 + min(amt2, (jug1-amt1)),
amt2 - min(amt2, (jug1-amt1))) or
waterJugSolver(amt1 - min(amt1, (jug2-amt2)),
amt2 + min(amt1, (jug2-amt2))))
else:
return False
print("Steps: ")
waterJugSolver(0, 0)

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
Steps:
00
40
43
03
30
33
42
02

REG NO: 211423243098 NAME:DHARANIDHARAN S


REG NO: 211423243098
REG
PROGRAM
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)
closed_set = set()
g = {}
parents = {}
g[start_node] = 0
parents[start_node] = start_node
while len(open_set) > 0:
n = None

for v in open_set:
if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):
n=v
if n == stop_node or Graph_nodes[n] == None:
pass
else:
for (m, weight) in get_neighbors(n):

if m not in open_set and m not in closed_set:


open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n
#if m in closed set,remove and add to open
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
print('Path does not exist!')
return None

if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
print('Path found: {}'.format(path))
return path

REG NO: 211423243098 NAME:DHARANIDHARAN S


open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None

def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None

def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 5,
'D': 7,
'E': 3,
'F': 6,
'G': 5,
'H': 3,
'I': 1,
'J': 0
}
return H_dist[n]

Graph_nodes = {
'A': [('B', 6), ('F', 3)],
'B': [('A', 6), ('C', 3), ('D', 2)],
'C': [('B', 3), ('D', 1), ('E', 5)],
'D': [('B', 2), ('C', 1), ('E', 8)],
'E': [('C', 5), ('D', 8), ('I', 5), ('J', 5)],
'F': [('A', 3), ('G', 1), ('H', 7)],
'G': [('F', 1), ('I', 3)],
'H': [('F', 7), ('I', 2)],
'I': [('E', 5), ('G', 3), ('H', 2), ('J', 3)],
}

aStarAlgo('A', 'J')

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
Path found: ['A', 'F', 'G', 'I', 'J']

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
import math
class GameState:

def init (self, board, player_turn):


self.board = board
self.player_turn = player_turn

def print_board(self):
for row in self.board:
print(' | '.join(cell if cell != '' else ' ' for cell in row))
print('-' * 5)

def evaluate(self):
win_conditions = [
[self.board[0][0], self.board[0][1], self.board[0][2]],
[self.board[1][0], self.board[1][1], self.board[1][2]],
[self.board[2][0], self.board[2][1], self.board[2][2]],
[self.board[0][0], self.board[1][0], self.board[2][0]],
[self.board[0][1], self.board[1][1], self.board[2][1]],
[self.board[0][2], self.board[1][2], self.board[2][2]],
[self.board[0][0], self.board[1][1], self.board[2][2]],
[self.board[2][0], self.board[1][1], self.board[0][2]]
]

for condition in win_conditions:


if condition == ['X', 'X', 'X']:
return 10
if condition == ['O', 'O', 'O']:
return -10
if any(cell == '' for row in self.board for cell in row):
return 0
return 0

def generate_possible_moves(self):
moves = []
for i in range(3):
for j in range(3):
if self.board[i][j] == '':
new_board = [row[:] for row in self.board]
new_board[i][j] = 'X' if self.player_turn else 'O'
moves.append(GameState(new_board, not self.player_turn))
return moves

def is_terminal(self):
return self.evaluate() != 0 or all(cell != '' for row in self.board for cell in row)

REG NO: 211423243098 NAME:DHARANIDHARAN S


def minimax(state, depth, alpha, beta, maximizing_player):
if state.is_terminal() or depth == 0:
return state.evaluate()

if maximizing_player:
max_eval = -math.inf
for move in state.generate_possible_moves():
eval = minimax(move, depth - 1, alpha, beta, False)
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
return max_eval
else:
min_eval = math.inf
for move in state.generate_possible_moves():
eval = minimax(move, depth - 1, alpha, beta, True)
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval

def best_move(state, depth):


best_eval = -math.inf if state.player_turn else math.inf
best_move = None
for move in state.generate_possible_moves():
eval = minimax(move, depth - 1, -math.inf, math.inf, not state.player_turn)
if (state.player_turn and eval > best_eval) or (not state.player_turn and eval < best_eval):
best_eval = eval
best_move = move
return best_move

current_board = [
['X', '', ''],
['', '', ''],
['', '', '']
]
initial_state = GameState(current_board, False)
print("Current Board State:")
initial_state.print_board()
depth = 3
move = best_move(initial_state, depth)
if move:
position = [(i, row.index('O')) for i, row in enumerate(move.board) if 'O' in row][0]
print(f"Best move for the opponent: {position}")
else:
print("No valid move found")

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
Current Board State:
X| |

| |

| |

Best move for the opponent: (0, 1)

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
import random
def generate_initial_state():
return [random.randint(0, 7) for _ in range(8)]

def heuristic(state):
conflicts = 0
for i in range(8):
for j in range(i + 1, 8):
if state[i] == state[j] or abs(state[i] - state[j]) == abs(i - j):
conflicts += 1
return conflicts

def generate_successors(state):
successors = []
for row in range(8):
for col in range(8):
if col != state[row]:
new_state = state[:]
new_state[row] = col
successors.append(new_state)
return successors

def first_choice_hill_climbing(max_iterations=1000):
iteration = 0
while iteration < max_iterations:
current_state = generate_initial_state()
current_heuristic = heuristic(current_state)
while current_heuristic > 0:
successors = generate_successors(current_state)
next_state = min(successors, key=lambda s: heuristic(s))
next_heuristic = heuristic(next_state)

if next_heuristic >= current_heuristic:


break
current_state = next_state
current_heuristic = next_heuristic

if current_heuristic == 0:
return current_state
iteration += 1
return None

def print_state(state):
board = [['0' for _ in range(8)] for _ in range(8)]
for row in range(8):
board[state[row]][row] = '1'
for row in board:
REG NO: 211423243098 NAME:DHARANIDHARAN S
print(' '.join(row))
print()
solution = first_choice_hill_climbing(max_iterations=5000)
if solution:
print("Solution found:")
print_state(solution)
else:
print("No solution found or local maximum reached.")

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
Solution found:
10000000
00000010
00001000
00000001
01000000
00010000
00000100
00100000

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
def is_valid(assignment, region, color, adjacency_list):
for neighbor in adjacency_list[region]:
if neighbor in assignment and assignment[neighbor] == color:
return False
return True

def backtrack(assignment, regions, colors, adjacency_list):


if len(assignment) == len(regions):
return assignment
for region in regions:
if region not in assignment:
for color in colors:
if is_valid(assignment, region, color, adjacency_list):
assignment[region] = color
result = backtrack(assignment, regions, colors, adjacency_list)
if result:
return result
del assignment[region]
return None
return None

def map_coloring(regions, colors, adjacency_list):


assignment = {}
return backtrack(assignment, regions, colors, adjacency_list)

def print_solution(solution):
if solution:
for region, color in solution.items():
print(f"Region {region} is colored {color}")
else:
print("No solution found")

regions = ['A', 'B', 'C']


colors = ['Red', 'Green', 'Blue']
adjacency_list = {
'A': ['B', 'C'],
'B': ['A', 'C'],
'C': ['A', 'B']
}
print("Map coloring solution is found:")
solution = map_coloring(regions, colors, adjacency_list)
print_solution(solution)

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
Map coloring solution is found:
Region A is colored Red
Region B is colored Green
Region C is colored Blue

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
import random
name = input("What is your name? ")
print("Good Luck ! ", name)

words = ['rainbow', 'computer', 'science', 'programming',


'python', 'mathematics', 'player', 'condition',
'reverse', 'water', 'board', 'geeks']
word = random.choice(words)

print("Guess the characters")


guesses = ''
turns = 12
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end=" ")
else:
print("_")
failed += 1

if failed == 0:
print("You Win")
print("The word is: ", word)
break
print()
guess = input("guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("Wrong")
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
What is your name? abi
Good Luck ! abi
Guess the characters
_
_
_
_
_
_

guess a character:g
Wrong
You have 11 more guesses
_
_
_
_
_
_

guess a character:r
_
_
_
_
_
r
guess a character:t
Wrong
You have 10 more guesses
_
_
_
_
_
r
guess a character:p
p_
_
_
_
r
guess a character:l
pl_
_
_
r
REG NO: 211423243098 NAME:DHARANIDHARAN S
guess a character:y
pl_
y_
r
guess a character:a
play_
r
guess a character:e
player

You Win

The word is: player

REG NO: 211423243098 NAME:DHARANIDHARAN S


PROGRAM
import numpy as np
import random
from time import sleep

def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))

def possibilities(board):
l = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)

def random_place(board, player):


selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)

def row_win(board, player):


for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)

def col_win(board, player):


for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)

def diag_win(board, player):


win = True
REG NO: 211423243098 NAME:DHARANIDHARAN S
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win

def evaluate(board):
winner = 0
for player in [1, 2]:
if (row_win(board, player) or
col_win(board, player) or
diag_win(board, player)):
winner = player
if np.all(board != 0) and winner == 0:
winner = -1
return winner

def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
print("Winner is: " + str(play_game()))

REG NO: 211423243098 NAME:DHARANIDHARAN S


OUTPUT
[[0 0 0]
[0 0 0]
[0 0 0]]
Board after 1 move
[[0 0 0]
[0 0 1]
[0 0 0]]
Board after 2 move
[[0 0 0]
[0 0 1]
[0 0 2]]
Board after 3 move
[[0 0 0]
[1 0 1]
[0 0 2]]
Board after 4 move
[[0 0 0]
[1 2 1]
[0 0 2]]
Board after 5 move
[[0 0 0]
[1 2 1]
[0 1 2]]
Board after 6 move
[[0 0 2]
[1 2 1]
[0 1 2]]
Board after 7 move
[[1 0 2]
[1 2 1]
[0 1 2]]
Board after 8 move
[[1 0 2]
[1 2 1]
[2 1 2]]
Winner is: 2

REG NO: 211423243098 NAME:DHARANIDHARAN S

You might also like