Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def algorithm(cities):
  4.     best_order = []
  5.     best_length = float('inf')
  6.  
  7.     for i_start, start in enumerate(cities):
  8.         order = [i_start]
  9.         length = 0
  10.  
  11.         i_next, next, dist = getClosest(start, cities, order)
  12.         length += dist
  13.         order.append(i_next)
  14.  
  15.         while len(order) < cities.shape[0]:
  16.             i_next, next, dist = getClosest(next, cities, order)
  17.             length += dist
  18.             order.append(i_next)
  19.  
  20.         print(order)
  21.  
  22.         if length < best_length:
  23.             best_length = length
  24.             best_order = order
  25.            
  26.     return best_order
  27.  
  28. def getClosest(city, cities, visited):
  29.     best_distance = float('inf')
  30.  
  31.     for i, c in enumerate(cities):
  32.  
  33.         if i not in visited:
  34.             distance = dist(city, c)
  35.  
  36.             if distance < best_distance:
  37.                 closest_city = c
  38.                 i_closest_city = i
  39.                 best_distance = distance
  40.  
  41.     return i_closest_city, closest_city, best_distance
  42.  
  43. def dist(c1, c2):
  44.     return np.hypot(c2[0] - c1[0], c2[1] - c1[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement