0

I am trying to solve the TSP (Traveling Salesman Problem) using the rbga.bin from the genealg package. I have matrix that stores the distances between the cities like this:

    [,1] [,2] [,3] [,4]
[1,]    0    2   10    4
[2,]    0    0   12   12
[3,]    0    0    0    5
[4,]    0    0    0    0

but I'm not able to code a proper evaluation function (even though I already saw some examples in documentation and on the web). I know a chromosome will be passed as a parameter to the evaluation function, but I don't know what operations to do to return a proper value.

josliber
  • 43,891
  • 12
  • 98
  • 133
Andres Alvarado
  • 196
  • 1
  • 11

1 Answers1

0

Basically, you are asking how to evaluate the length of a path given the endpoints on that path and a distance matrix (for path 1-3-2-4, you want d13+d32+d24+d41). You can do this with matrix indexing and the sum function. Let's consider your distance matrix and solution 1-3-2-4 (since the TSP is typically posed in a symmetric form, I've made it symmetric):

(d <- matrix(c(0, 2, 10, 4, 2, 0, 12, 12, 10, 12, 0, 5, 4, 12, 5, 0), nrow=4))
#      [,1] [,2] [,3] [,4]
# [1,]    0    2   10    4
# [2,]    2    0   12   12
# [3,]   10   12    0    5
# [4,]    4   12    5    0
sln <- c(1, 3, 2, 4)

Now you can grab matrix indexes from your solution and pull the distances, summing them for your final evaluation:

(idx <- cbind(sln, c(tail(sln, -1), sln[1])))
# [1,]   1 3
# [2,]   3 2
# [3,]   2 4
# [4,]   4 1
d[idx]
# [1] 10 12 12  4
sum(d[idx])
# [1] 38
josliber
  • 43,891
  • 12
  • 98
  • 133