-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgreedy.py
More file actions
47 lines (33 loc) · 941 Bytes
/
greedy.py
File metadata and controls
47 lines (33 loc) · 941 Bytes
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
import numpy as np
def algorithm2(cities):
best_order = []
best_length = float('inf')
for i_start, start in enumerate(cities):
order = [i_start]
length = 0
i_next, next, dist = get_closest(start, cities, order)
length += dist
order.append(i_next)
while len(order) < cities.shape[0]:
i_next, next, dist = get_closest(next, cities, order)
length += dist
order.append(i_next)
#print(order)
if length < best_length:
best_length = length
best_order = order
return best_order, best_length
def get_closest(city, cities, visited):
best_distance = float('inf')
for i, c in enumerate(cities):
if i not in visited:
distance = dist_squared(city, c)
if distance < best_distance:
closest_city = c
i_closest_city = i
best_distance = distance
return i_closest_city, closest_city, best_distance
def dist_squared(c1, c2):
t1 = c2[0] - c1[0]
t2 = c2[1] - c1[1]
return t1**2 + t2**2