0% found this document useful (0 votes)
1 views8 pages

Assiment 2

The document contains two code implementations: one for the Hill Climbing algorithm to solve the Traveling Salesman Problem (TSP) and another for the A* algorithm to find the shortest path in a graph. The TSP code generates random paths and optimizes them, while the A* code utilizes a heuristic to navigate through a graph defined by adjacency lists. Both algorithms are demonstrated with example inputs for testing.

Uploaded by

chandan52chd1
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)
1 views8 pages

Assiment 2

The document contains two code implementations: one for the Hill Climbing algorithm to solve the Traveling Salesman Problem (TSP) and another for the A* algorithm to find the shortest path in a graph. The TSP code generates random paths and optimizes them, while the A* code utilizes a heuristic to navigate through a graph defined by adjacency lists. Both algorithms are demonstrated with example inputs for testing.

Uploaded by

chandan52chd1
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/ 8

ASSIGNMENT 2

SUBMITTED BY :- MADHAV AGRAWAL


Name :Chandan Kumar
SID :- 20104098 Sid:20104018
EE Branch:EE

1. CODE FOR TSB

import random

def DifferentPaths(tsp):

cities = list(range(len(tsp)))
solution = [0]

for i in range(len(tsp)-1):

randomCity = cities[random.randint(1, len(cities) - 1)]

solution.append(randomCity)
cities.remove(randomCity)

#print(solution)

return solution

# route length after visiting all the cities

def LenghtOfPath(tsp, solution):

LenghtOfPath = 0

for i in range(len(solution)):
LenghtOfPath += tsp[solution[i - 1]][solution[i]]

#print(LenghtOfPath)

return LenghtOfPath
def getNeighbours(solution):
neighbours = []

for i in range(1,len(solution)):

for j in range(i + 1, len(solution)):

neighbour = solution.copy()
neighbour[i] = solution[j]

neighbour[j] = solution[i]

neighbours.append(neighbour)

#print(neighbours)
return neighbours

def getBestNeighbour(tsp, neighbours):

bestRouteLength = LenghtOfPath(tsp, neighbours[0]) # best route will be find after


bestNeighbour = neighbours[0]

for neighbour in neighbours:

currentRouteLength = LenghtOfPath(tsp, neighbour)

if currentRouteLength < bestRouteLength:


bestRouteLength = currentRouteLength

bestNeighbour = neighbour

#print(bestNeighbour, bestRouteLength)

return bestNeighbour, bestRouteLength

def hillClimbingAlgo(tsp):

currentSolution = DifferentPaths(tsp)

currentRouteLength = LenghtOfPath(tsp, currentSolution)


neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)

while bestNeighbourRouteLength < currentRouteLength:

currentSolution = bestNeighbour

currentRouteLength = bestNeighbourRouteLength

neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)

currentSolution.append(0)

for i in range(len(currentSolution)):
if currentSolution[i] == 0:

currentSolution[i] = 'A'

elif currentSolution[i] == 1:

currentSolution[i] = 'B'
elif currentSolution[i] == 2:

currentSolution[i] = 'C'

elif currentSolution[i] == 3:

currentSolution[i] = 'D'
elif currentSolution[i] == 4:

currentSolution[i] = 'E'

return currentSolution

tsp = [

[0, 7, 12, 10, 13],

[7, 0, 14, 10, 12],


[12, 14, 0, 14, 9],
[10, 10, 14, 0, 7],

[13, 12, 9, 7, 0]
]

print(hillClimbingAlgo(tsp))

2. CODE FOR A*

from collections import deque

class Graph:
def __init__(self, adjac_lis):

self.adjac_lis = adjac_lis

def get_neighbors(self, v):

return self.adjac_lis[v]

# This is heuristic function which is having equal values for all nodes

def h(self, n):

H ={

'A': 1,
'B': 1,

'C': 1,

'D': 1,

'E': 1,
'G': 1

return H[n]

def a_star_algorithm(self, start, stop):

open_lst = set([start])
closed_lst = set([])

curr_dist_of_nodes = {}

curr_dist_of_nodes[start] = 0
adjac_nodes = {}

adjac_nodes[start] = start
while len(open_lst) > 0:

n = None

for v in open_lst:
if n == None or curr_dist_of_nodes[v] + self.h(v) < curr_dist_of_nodes[n] + self.h(n):

n = v;

if n == None:

print('Path does not exist!')

return None

if n == stop:

reconst_path = []

while adjac_nodes[n] != n:

reconst_path.append(n)

n = adjac_nodes[n]

reconst_path.append(start)

reconst_path.reverse()

print('Path found: {}'.format(reconst_path))


return reconst_path
# for all the neighbors of the current node do
for (m, weight) in self.get_neighbors(n):

if m not in open_lst and m not in closed_lst:

open_lst.add(m)
adjac_nodes[m] = n

curr_dist_of_nodes[m] = curr_dist_of_nodes[n] + weight

else:

if curr_dist_of_nodes[m] > curr_dist_of_nodes[n] + weight:

curr_dist_of_nodes[m] = curr_dist_of_nodes[n] + weight

adjac_nodes[m] = n

if m in closed_lst:

closed_lst.remove(m)

open_lst.add(m)

open_lst.remove(n)

closed_lst.add(n)

print('Path does not exist!')

return None

adjac_lis = {
'A': [('B', 2), ('E', 3)],
'B': [('A', 2),('C',1),('G',9)],

'C': [('B', 1)],


'D': [('E',6),('G',1)],

'E': [('A',3),('D',6)],

'G': [('D',1),('B',9)]

}
graph1 = Graph(adjac_lis)

graph1.a_star_algorithm(input("START NODE: "), input("GOAL NODE: "))

You might also like