#Simulate positions for n=15 cities
set.seed(2323)
p = 15
pos = data.frame(x=runif(p),y=runif(p))

par(mfrow=c(1,1))
plot(pos)
#dev.copy2pdf(file="../doc/example_trav_sale.pdf")

#par(mfrow=c(3,1))
plot(pos)

#Calculate pairwise distances between cities
d = as.matrix((dist(pos,diag=TRUE,upper=TRUE)))
#image(d)

#Convert to vector in order to access many components at a time
d = as.vector(d)

#Random order of visits
theta = sample(1:p,p)
#Convert sequential pairs into index in the d-vector
ind = (theta[-p]-1)*p+theta[-1]  # lookup in distance vector 
#Calculate total distance of order
V = sum(d[ind])
Vseq = V


#Perform neighbor search, changing best two components
more = TRUE
while(more)
{
  V2opt = V
  i1opt = NA
  # loop below determines the best pair to swap
  for(i1 in 1:(p-1))
    for(i2 in (i1+1):p)
    {
      theta2 = theta
      theta2[i1] = theta[i2]
      theta2[i2] = theta[i1]
      ind2 = (theta2[-p]-1)*p+theta2[-1]  
      V2 = sum(d[ind2])
      if(V2<V2opt)
      {
        V2opt = V2
        i1opt = i1
        i2opt = i2
      }
    }
    more = FALSE
    if(V2opt<V) ## if the best swap is better than current optimum  update and continiue
    {
      theta2 = theta
      theta2[i1opt] = theta[i2opt]
      theta2[i2opt] = theta[i1opt]
      theta = theta2
      V = V2opt
      Vseq = c(Vseq,V)
      more = TRUE
  }
}
par(mfrow=c(2,1),mar=c(0.5,1,0.5,1))
plot(pos)
lines(pos[theta,1],pos[theta,2])
#dev.copy2pdf(file="../doc/travel_sale_opt1.pdf")
plot.ts(Vseq)
show(min(Vseq))
