Example #1
0
def twoopt(tour):

  nearestneighbor.updateindexes(tour,0,len(tour))

  for a in list(tour):

    for c in [x.city for x in a.neighbors[:-1]]:

      if a.index>c.index: a,c = c,a

      b = tour[a.index+1]
      d = tour[(c.index+1)%len(cities)]

      if b is not c and distance(a,b) + distance(c,d) > distance(a,c) + distance(b,d):
        swap(tour,b,c)
def twoopt(tour):

  swapcount = 0

  nearestneighbor.updateindexes(tour,0,len(tour))

  for a in list(tour):

    for c in [x.city for x in a.neighbors[:-1]]:

      if a.index>c.index: a,c = c,a

      b = tour[a.index+1]
      d = tour[(c.index+1)%len(cities)]

      if b is not c and distance(a,b) + distance(c,d) > distance(a,c) + distance(b,d):
        swap(tour,b,c)
        swapcount +=1

  return swapcount
def swap(tour,b,c):
  #print "swaping city%d @%d and city%d @%d"%(b.id,b.index,c.id,c.index)
  tour[b.index:c.index+1] = reversed(tour[b.index:c.index+1])
  nearestneighbor.updateindexes(tour,b.index,c.index+1)
Example #4
0
def swap(tour,b,c):
  #print "swaping city%d @%d and city%d @%d"%(b.id,b.index,c.id,c.index)
  tour[b.index:c.index+1] = reversed(tour[b.index:c.index+1])
  nearestneighbor.updateindexes(tour,b.index,c.index+1)