# Number of towns N=25 # Creating the random map & the distance matrix #townz=matrix(rnorm(2*N)+runif(2*N)*6,ncol=2) dist=sqrt(( townz[,1]%*%t(rep(1,N))-rep(1,N)%*%t(townz[,1]) )^2 + ( townz[,2]%*%t(rep(1,N))-rep(1,N)%*%t(townz[,2]) )^2) dev.off() X11(w=12,h=8) plot(townz,pch=19,col="red") # Cost of a path coss=function(perm){ co=dist[perm[N],perm[1]] for (t in 1:(N-1)) co=co+dist[perm[t],perm[t+1]] co } # Plot of a path plath=function(perm,tranz){ # browser() lines(townz[tranz,1],townz[tranz,2],col="white",lwd=2) lines(c(townz[tranz[N],1],townz[tranz[1],1]), c(townz[tranz[N],2],townz[tranz[1],2]),col="white",lwd=2) lines(townz[perm,1],townz[perm,2],col="sienna",lwd=2) lines(c(townz[perm[N],1],townz[perm[1],1]), c(townz[perm[N],2],townz[perm[1],2]),col="sienna",lwd=2) points(townz,pch=19,col="red") } lastplath=function(perm){ lines(townz[perm,1],townz[perm,2],col="steelblue",lty=2,lwd=2) lines(c(townz[perm[N],1],townz[perm[1],1]), c(townz[perm[N],2],townz[perm[1],2]),col="steelblue",lty=2,lwd=2) } # Random start #overperm=c(1,sample(2:N)) refperm=overperm plath(refperm,refperm) lastplath(overperm) overcos=coss(overperm) refcos=overcos print(refcos) #alpha=refcos # SA # under the provision perm[1]=1 for (i in 1:5000){ perm=c(1,sample(2:N)) newcos=coss(perm) if (newcos