\small
\texttt{\# Simulated Annealing for Traveling Salesman\\
\\
pathPermutations <- function(sigma)\{\\
\hspace*{0.5cm}	l <- length(sigma)\\
\hspace*{0.5cm}	num <- choose(l,2) + 1\\
\\
\hspace*{0.5cm}	r <- matrix(0,nrow=num,ncol=l)\\
\\
\hspace*{0.5cm}	c <- 1\\
\hspace*{0.5cm}	for( i in 1:(l-1) )\{\\
\hspace*{1cm}		for( j in (i+1):l )\{\\
\hspace*{1.5cm}			r[c,] <- sigma\\
\hspace*{1.5cm}			r[c,i] <- sigma[j]\\
\hspace*{1.5cm}			r[c,j] <- sigma[i]\\
\hspace*{1.5cm}			c <- c + 1\\
\hspace*{1cm}		\}\\
\hspace*{0.5cm}	\}\\
\hspace*{0.5cm}	r[c,] <- sigma\\
\\
\hspace*{0.5cm}	return(r)\\
\}\\
\\
H <- function(path,D)\{\\
\hspace*{0.5cm}	l <- length(path)\\
\hspace*{0.5cm}	d <- D[path[l],path[1]]\\
\hspace*{0.5cm}	for( i in 2:(l) )\{\\
\hspace*{1cm}		d <- d + D[path[i-1],path[i]]\\
\hspace*{0.5cm}	\}\\
\hspace*{0.5cm}	return(d)\\
\}\\
\\
allPn <- function(s)\{\\
\hspace*{0.5cm}	library(combinat)\\
\hspace*{0.5cm}	l <- length(s)\\
\hspace*{0.5cm}	n <- factorial(l)\\
\hspace*{0.5cm}	t(matrix(unlist(permn(sort(s))),ncol=n,nrow=l))\\
\}\\
\\
pi.term <- function(h.i,h.j,beta)\{\\
\hspace*{0.5cm}	r <- exp( -beta * (h.j - h.i) )\\
\hspace*{0.5cm}	if( h.j - h.i == 0 )\{\\
\hspace*{1cm}		r <- 1\\
\hspace*{0.5cm}	\}\\
\hspace*{0.5cm}	return(r)\\
\}\\
\\
nextPath <- function(original,beta,D)\{\\
\hspace*{0.5cm}	l <- length(original)\\
\hspace*{0.5cm}	n <- factorial(l)\\
\hspace*{0.5cm}	paths <- pathPermutations(original)\\
\\
\\
\hspace*{0.5cm}	lpt <- choose(l,2) + 1\\
\hspace*{0.5cm}	p <- numeric(lpt)\\
\\
\hspace*{0.5cm}	this <- lpt\\
\hspace*{0.5cm}	c <- 1\\
\\
\hspace*{0.5cm}	for( i in 1:(lpt-1) )\{\\
\hspace*{1cm}		pi\_i <- sDist(beta,paths[this,],D)\\
\hspace*{1cm}		pi\_j <- sDist(beta,paths[i,],D)\\
\\
\hspace*{1cm}		ratio <- pi.term(H(paths[this,],D),H(paths[i,],D),beta)\\
\\
\hspace*{1cm}		p[i] <- 1 / lpt\\
\hspace*{1cm}		\\
\hspace*{1cm}		if( ratio < 1 )\{\\
\hspace*{1.5cm}			p[i] <- (1/lpt) * ratio \\
\hspace*{1cm}		\}\\
\\
\hspace*{0.5cm}	\}\\
\\
\hspace*{0.5cm}	p[this] <- 1 - sum(p)\\
\\
\hspace*{0.5cm}	ranU <- runif(1)\\
\hspace*{0.5cm}	c <- 1\\
\hspace*{0.5cm}	rtotal <- p[1]\\
\\
\hspace*{0.5cm}	while( rtotal < ranU )\{\\
\hspace*{1cm}		c <- c + 1\\
\hspace*{1cm}		rtotal <- rtotal + p[c]\\
\hspace*{0.5cm}	\}\\
\\
\hspace*{0.5cm}	return(paths[c,])\\
\}\\
}
