0% found this document useful (0 votes)
12 views17 pages

AAI Journal

The document outlines a series of practical programming exercises completed by Aditya Ojha, including implementations of algorithms such as Breadth-first search, Depth-first search, an 8-Puzzle solver, Tic-Tac-Toe, the Travelling Salesman Problem, Tower of Hanoi, and an Artificial Neural Network (ANN). Each practical includes code snippets and explanations of the algorithms used. The document serves as a record of the programming tasks performed for a TYBSCIT course.

Uploaded by

Anupama Jawale
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)
12 views17 pages

AAI Journal

The document outlines a series of practical programming exercises completed by Aditya Ojha, including implementations of algorithms such as Breadth-first search, Depth-first search, an 8-Puzzle solver, Tic-Tac-Toe, the Travelling Salesman Problem, Tower of Hanoi, and an Artificial Neural Network (ANN). Each practical includes code snippets and explanations of the algorithms used. The document serves as a record of the programming tasks performed for a TYBSCIT course.

Uploaded by

Anupama Jawale
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

Aditya Ojha TYBSCIT - A030 45207210064

Index
Sr. No. Date Subject Remark
1 26/06/2024 Practical – 1
Perform Breadth-first and Depth-first search

2 10/07/2024 Practical – 2
8-Puzzle Problem

3 24/07/2024 Practical – 3
Tic-Tac-Toe using Random Numbers

4 02/08/2024 Practical – 4
Travelling Salesman

5 28/08/2024 Practical – 5
Tower of Hanoi

6 29/08/2024 Practical – 6
ANN
Aditya Ojha TYBSCIT - A030 45207210064

Practical – 1
Q) Write a program to perform breadth-first search on this graph.

Code:

visited = []
queue = []
def bfs(visited, graph, node):
[Link](node)
[Link](node)
while queue:
m = [Link](0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)

graph = {
'5' : ['3','7'],
'3' : ['2','4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

print("Following is the Breadth-First Search")


bfs(visited, graph, '5')
Aditya Ojha TYBSCIT - A030 45207210064

Output:

Q) Write a program to perform breadth-first search on this graph.

Code:

visited = []
queue = []
def bfs(visited, graph, node):
[Link](node)
[Link](node)
while queue:
m = [Link](0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)

graph = {
'R' : ['S','V'],
'S' : ['W'],
'V' : [],
'W' : ['T','X'],
'T' : ['X','U'],
'X' : ['Y'],
Aditya Ojha TYBSCIT - A030 45207210064

'U' : ['Y'],
'Y' : []
}

print("\nFollowing is the Breadth-First Search")


bfs(visited, graph, 'R')

Output:

Q) Write a program to perform depth-first search on this graph.

Code:

graph = {
'R' : ['S','V'],
'S' : ['W'],
'V' : [],
'W' : ['T','X'],
'T' : ['X','U'],
'X' : ['Y'],
'U' : ['Y'],
'Y' : []
}

def dfs(graph, start):


visited = set()
stack = [start]
while stack:
Aditya Ojha TYBSCIT - A030 45207210064

vertex = [Link]()
if vertex not in visited:
[Link](vertex, end = " ")
print(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
[Link](neighbor)

print("Following is the Depth-First Search")


dfs(graph, 'R')

Output:
Aditya Ojha TYBSCIT - A030 45207210064

Practical – 2
Q) Write a program to solve an 8-Puzzle and calculate the minimum number moves for it

Code:

def solve(board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return 0
return get_paths(dict)

def get_paths(dict):
cnt = 0
while True:
current_nodes = [x for x in dict if dict[x] == cnt]
if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = find_next(node)
for move in next_moves:
if move not in dict:
dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1

def find_next(node):
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = [Link](0)
Aditya Ojha TYBSCIT - A030 45207210064

for move in moves[pos_0]:


new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
[Link](tuple(new_node))
return results

matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]

print(solve(matrix))

Output:

Q) Write a program to solve an 8-Puzzle and mention each move and step

def solve(board):
moves = [] # To store the sequence of moves
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = (0, None) # Change to store both move count and previous
state
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return print_moves(dict, flatten, moves)
return get_paths(dict, moves)

def get_paths(dict, moves):


cnt = 0
while True:
current_nodes = [x for x in dict if dict[x][0] == cnt]
if len(current_nodes) == 0:
return -1
for node in current_nodes:
next_moves = find_next(node)
for move in next_moves:
if move not in dict:
Aditya Ojha TYBSCIT - A030 45207210064

dict[move] = (cnt + 1, node) # Store previous state for


backtrack
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return print_moves(dict, move, moves)
cnt += 1

def find_next(node):
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}
results = []
pos_0 = [Link](0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
[Link](tuple(new_node))
return results

def print_moves(dict, final_state, moves):


current_state = final_state
while current_state in dict and dict[current_state][1] is not None:
[Link](current_state)
current_state = dict[current_state][1]
[Link](current_state)
[Link]() # Reverse to print moves in correct order
for i, move in enumerate(moves):
print(f"Move {i + 1}:")
print_board(move)
print()
return len(moves) - 1

def print_board(board):
for i in range(0, 9, 3):
print(board[i:i+3])
Aditya Ojha TYBSCIT - A030 45207210064

matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print(f"Minimum number of moves: {solve(matrix)}")

Output:
Aditya Ojha TYBSCIT - A030 45207210064

Practical – 3
Q) Write a program to create a Tic-Tac-Toe game with random numbers in Python

Code:

import numpy as np
import random
from time import sleep

# Creates an empty board


def create_board():
return([Link]([[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:
[Link]((i, j))
return(l)

def random_place(board, player):


selection = possibilities(board)
current_loc = [Link](selection)
board[current_loc] = player
return(board)

def user_place(board, player):


selection = possibilities(board)
print("\nUser's Turn:")
options = []
for i, sel in enumerate(selection):
print(str(i + 1) + ". " + str(sel))
[Link](i)
print(options)
pos = -1
while pos not in options:
pos = int(input("Enter a position:"))
if (pos - 1) in options:
break
print("Enter valid position.")
board[selection[pos - 1]] = player
return(board)
Aditya Ojha TYBSCIT - A030 45207210064

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
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
Aditya Ojha TYBSCIT - A030 45207210064

if [Link](board != 0) and winner == 0:


winner = -1
return winner

def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)
order = [1, 2]
[Link](order)
while winner == 0:
for player in order:
if player == 1:
board = user_place(board, player)
else:
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)

ans = play_game()
if ans == 1:
print("User wins.")
elif ans == 2:
print("CPU wins.")
else:
print("The game is a draw")
Aditya Ojha TYBSCIT - A030 45207210064

Output
Aditya Ojha TYBSCIT - A030 45207210064

Practical – 4
Q) Write a Program to implement the Travelling Salesman Problem using Python.

Code

from sys import maxsize


from itertools import permutations

def travelling_salesman(graph, start_vertex):


num_vertices = len(graph)
vertices = [i for i in range(num_vertices) if i != start_vertex]
min_path = maxsize
for perm in permutations(vertices):
current_path_weight = 0
current_vertex = start_vertex
for vertex in perm:
current_path_weight += graph[current_vertex][vertex]
current_vertex = vertex
current_path_weight += graph[current_vertex][start_vertex]
min_path = min(min_path, current_path_weight)
return min_path

graph = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
start_vertex = 0
print(f"Minimum path cost: {travelling_salesman(graph, start_vertex)}")

Output
Aditya Ojha TYBSCIT - A030 45207210064

Practical – 5
Q) Write a Program to implement Tower of Hanoi.

Code

def tower_of_hanoi(n , from_rod, to_rod, aux_rod):


if n == 1:
print("Move disk 1 from rod", from_rod, "to rod", to_rod)
return
tower_of_hanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk",n, "from rod", from_rod, "to rod", to_rod)
tower_of_hanoi(n-1, aux_rod, to_rod, from_rod)

n = 4
tower_of_hanoi(n, 'A', 'C', 'B')

Output
Aditya Ojha TYBSCIT - A030 45207210064

Practical – 6
Q) Write a Program to implement ANN

Code

def sigmoid(x):
return 1 / (1 + [Link](-x))

def sigmoid_derivative(x):
return(x * (1 - x))

import numpy as np;

input_layer_size = 3;
hidden_layer_size = 4;
output_layer_size = 1;

weights_1 = [Link](input_layer_size, hidden_layer_size);


weights_2 = [Link](hidden_layer_size, output_layer_size);

print("weights_1=\n", weights_1);
print("weights_2=\n", weights_2);

x = [Link]([[0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]);


y = [Link]([[0], [1], [1], [0]]);

print("x=\n", x);
print("y=\n", y);

for i in range (100000):


input_hidden_layer = [Link](x, weights_1);
output_hidden_layer = [Link](input_hidden_layer, weights_2);
ycap = sigmoid(output_hidden_layer);
error = ycap - y;
output_layer_delta = error * sigmoid_derivative(ycap);
hiddden_layer_error = output_layer_delta.dot(weights_2.T);
hidden_layer_delta =
hiddden_layer_error*sigmoid_derivative(output_hidden_layer);
learning_rate = 0.5;
weights_2 += output_hidden_layer.[Link](output_layer_delta) * learning_rate;
weights_1 += [Link](hidden_layer_delta) * learning_rate;

print("ycap=", ycap);
Aditya Ojha TYBSCIT - A030 45207210064

Output

You might also like