Sunday, March 26, 2017

Nearest neighbor lists

Note that neighbor lists are used to speed up the process of optimization, and using them may cost slightly worse quality of resulting tours, even if it not always occurs.

type
  Neighbor_Matrix = array [City_Number, seq[City_Number]]
proc Build_Neighbors_Matrix(No_Of_Neigbors: int = N-1): Neighbor_Matrix =
  ## Builds array of No_Of_Neigbors nearest neighbors of each city
  # neighbor[i][j] is j-th nearest neighbour of city number i.
  var
    currentCity, otherCity: City_Number
    idx: int
    neighbors_of_currentCity: seq[City_Number]
    neighbor: Neighbor_Matrix

  newSeq(neighbors_of_currentCity, N-1)
  for currentCity in 0 .. N-1:
    # create sequence of all neighbors of current city:
    idx = 0
    for otherCity in 0 .. N-1:
      if otherCity != currentCity:
        neighbors_of_currentCity[idx] = otherCity
        idx = idx + 1

    # Sort elements in neighbors_of_currentCity by ascending distance
    # to currentCity (use any convenient method of sorting), then take
    # first No_Of_Neigbors cities from the result.
    sort(neighbors_of_currentCity) do (x,y: City_Number) -> int:
      result = cmp(distance(currentCity, x), distance(currentCity, y))

    neighbor[currentCity] = @[]
    setlen(neighbor[currentCity], No_Of_Neigbors)
    for idx in 0 .. No_Of_Neigbors-1:
      neighbor[currentCity][idx] = neighbors_of_currentCity[idx]
  result = neighbor

No comments:

Post a Comment