Search code examples
rtraveling-salesman

TSP in R, wrong tour length


I have got simple distance table(matrix):

datalist <- data.table(V1=c(0, 28635.76, 16496.41), V2=c(28635.76, 0, 22032.14), V3 = c(16496.41, 22032.14, 0))

When I am testing TSP algorithm from R package "TSP" I am getting result of tour length: 98559.14. But when I am adding distances "by hand" my result is 16496.41+22032.14+28635.76 = 67164.31 = tour_length(tour). Rest of my code:

  tspObj <- ETSP(datalist)
  tour <- solve_TSP(tspObj, start = 1, method = "two_opt")
  #tour length
  tour_length(tour)

Anyone knows why I get two different results?


Solution

  • The E in ETSP stands for "Euclidean". This function interprets V1, V2, V3 as 3 points in 3-dimensional Euclidean space, not as the rows of a distance matrix (as you seem to be thinking). Note that:

    > sum(sqrt(sum((V1-V2)^2)) + sqrt(sum((V1-V3)^2)) + sqrt(sum((V2-V3)^2)))
    [1] 98559.14
    

    There is another constructor called simply TSP. You can't directly feed it a data table, but the following works:

    > tspObj <- TSP(as.dist(datalist))
    > tour <- solve_TSP(tspObj, start = 1, method = "two_opt")
    > tour
    object of class ‘TOUR’ 
    result of method ‘two_opt’ for 3 cities
    tour length: 67164.31