-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhillClimbing.py.txt
57 lines (55 loc) · 2.04 KB
/
hillClimbing.py.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import random
cities=list(range(len(tcp)))
solution=[]
for i in range(len(tcp)):
randomCity = cities[random.randint(0,len(cities)-1)]
solution.append(randomCity)
cities.remove(randomCity)
return solution
def routeLength (tsp, solution):
routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength
def getNeighbours (solution):
neighbours = []
for i in range(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("-------Traversing-------")
print(neighbours)
return neighbours
def getBestNeighbour (tsp, neighbours) :
bestRouteLength = routelength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(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)
print("-----------Answer----------")
return currentSolution, currentRouteLength
def main():
tsp=[
[923,529,297,693,907],
[542,693,401,280,758],
[272,470,988,509,592],
[913,831,740,858,451]
]
print(hillClimbing(tsp))
if __name__ == "__main__":
main()