0

This is related to travelling salesman problem. First all permutations need to be generated and then the destination (same as origin) attached. I.e.: 1) abcd abdc ....

2) abcda abdca ....a

I have all the distances and only need an algorithm to sum them up. I wonder if there is an algorithm (C preferable) I can use for this or if there is a ready-made solution somewhere.

3
  • So, given "abcde" you want to sum the distances ab, bc, cd, de? Commented Oct 21, 2010 at 22:53
  • Do you need to get the permutations, too? Commented Oct 21, 2010 at 23:04
  • I have a list of permutations, like abcda Commented Oct 21, 2010 at 23:12

1 Answer 1

2

This is kinda trivial.

int sum = 0; for (i = 0; i < length-1; i++) { sum += distance[group[i]][group[i+1]]; } 

Where distance is a 2d array (matrix if you will) that holds the distance between the two nodes. group should be an array or vector or the nodes in order traveled.

If you also need to get each permutation, use next_permutation.

Here's a brief example of what distance might be:

int distance[4][4] = { {0,2,1,0}, {2,0,1,2}, {1,1,0,1}, {0,2,1,0}, }; 

Note that this will be a symmetric matrix for your problem.

Sign up to request clarification or add additional context in comments.

3 Comments

That's meant to be the length of the list of nodes. It should always be the same for your situation (5 for the example you gave).
I'm working on a switch statement for the distance function and I don't want to type the same distances with source and destination reversed. Is there something else I can do?
Don't use a switch statement. Put the distances in a matrix (type vector<vector<int> >). Then you can just return distances[i][i+1]. The subscripts should be the node values. So for nodes a and b, you might do distances[0][1]. Furthermore, you can first put the two parameters in increasing order, so given b, a, you'd switch them to a, b.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.