0

I am trying to implement the Traveling Salesperson Algorithm (TSP) using a .txt file. The files read like a .csv with "," between each number. And example of the file content could include:

 "0,8,6,5,2,9
  8,0,14,11,10,17
  6,14,0,3,5,6
  5,11,3,0,4,9
  2,10,5,4,0,7
  9,17,6,9,7,0"

I would like the output to look something like:

 Enter number of nodes:
  6
 Matrix file "FILENAME.txt" being read in: 

 "0,8,6,5,2,9
  8,0,14,11,10,17
  6,14,0,3,5,6
  5,11,3,0,4,9
  2,10,5,4,0,7
  9,17,6,9,7,0"

 Nearest neighbor is running:
  A,E,D,C,F,B,A  Cost = 40
  B,A,E,D,C,F,B  Cost = 40
  C,D,E,A,B,F,C  Cost = 40
  D,C,E,A,B,F,D  Cost = 44
  E,A,D,C,F,B,E  Cost = 43
  F,C,D,E,A,B,F  Cost = 40

 The best solution for neighbors visited is as follows:
  A,B,D,C,F,E,A  Cost = 37

The code that I have thus far is in Java and it does in fact have the correct algorithm, it prints the file, and it attempts to print the best solution. It does not however incorporate cost. It looks as follows:

package TSP;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class TSPNearestNeighbour {

private int numberOfNodes;
private Stack<Integer> stack;

public TSPNearestNeighbour() {
    stack = new Stack<Integer>();
}

/* Traveling Saleperson Algorithm */
public void tsp(int adjacencyMatrix[][]) {

    numberOfNodes = adjacencyMatrix[1].length - 1;
    int[] visited = new int[numberOfNodes + 1];
    visited[1] = 1;
    stack.push(1);
    int element, dst = 0, i;
    int min = Integer.MAX_VALUE;
    boolean minFlag = false;
    System.out.print(1 + "\t");

    while (!stack.isEmpty()) {
        element = stack.peek();
        i = 1;
        min = Integer.MAX_VALUE;
        while (i <= numberOfNodes) {
            if (adjacencyMatrix[element][i] > 1 && visited[i] == 0) {
                if (min > adjacencyMatrix[element][i]) {
                    min = adjacencyMatrix[element][i];
                    dst = i;
                    minFlag = true;
                }
            }
            i++;
        }
        if (minFlag) {
            visited[dst] = 1;
            stack.push(dst);
            System.out.print(dst + "\t");
            minFlag = false;
            continue;
        }
        stack.pop();
    }
}

/* Point to file that is going to be read in */
private static final String FILENAME = "C:\\6.txt";

/* Main */
public static void main(String... arg) throws IOException {

    BufferedReader bufferReader = null;
    FileReader fileReader = null;
    int number_of_nodes;
    Scanner scanner = null;
    String sCurrentLine;

    try {
        /* number of nodes */
        System.out.println("Enter the number of nodes in the graph");
        scanner = new Scanner(System.in);
        number_of_nodes = scanner.nextInt();

        /* read from designated file */
        System.out.println("Matrix file being read in: ");
        bufferReader = new BufferedReader(new FileReader(FILENAME));
        while ((sCurrentLine = bufferReader.readLine()) != null) {
            /* print the file to the console */
            System.out.println(sCurrentLine);
        }

        /* re-scan the file */
        int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
        scanner = new Scanner(new File(FILENAME));
        while (scanner.hasNextInt()) {
            for (int i = 1; i <= number_of_nodes; i++) {
                /* breaks here */
                String[] array = sCurrentLine.split(",", number_of_nodes);
                for (int j = 1; j <= number_of_nodes; j++) {
                    adjacency_matrix[i][j] = scanner.nextInt();
                }
            }

            for (int i = 1; i <= number_of_nodes - 1; i++) {
                for (int j = 1; j <= number_of_nodes - 1; j++) {
                    if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0) {
                        adjacency_matrix[j][i] = 1;
                    }
                }
            }
        }
        System.out.println("The best solution for citys are visited as follows");
        TSPNearestNeighbour tspNearestNeighbour = new TSPNearestNeighbour();
        tspNearestNeighbour.tsp(adjacency_matrix);


        /* exception for if the file you name does not exist, the program does not crash */
    } catch (IOException e) {
    } finally {
        try {
            if (bufferReader != null) {
                bufferReader.close();
            }
            if (fileReader != null) {
                fileReader.close();
            }
        } catch (IOException ex) {
        }
    }

    scanner.close();
}

Can someone please help me incorporate cost for each permutation, read the file by integers as if it is a Matrix and then give the most optimal solution. Thank you.

  • You say 'The files read like a .csv with `","` between each number', yet your example has ' ,' (space comma ... and occasional new lines) between each number. Please disambiguate your question. – Tibrogargan Apr 20 '17 at 19:28
  • @Tibrogargan Thank you for your constructive criticism, it has been fixed. – Girls.Gone.Wired Apr 20 '17 at 19:36
  • Your question still needs work. A CSV file is comma separated by definition. Your calling it out as if it is an exception is confusing. You would be better off describing what the input file actually contains. Are these numbers city IDs? Are they distances between cities? Where does `A,B,C,D,E,F` come from? – Tibrogargan Apr 20 '17 at 21:02
  • Your code only ever visits each city once, so there is only one permutation (I believe you could easily calculate the cost of that permutation by accumulating `adjacency_matrix[element][dst]` when `minFlag` is true .. assuming the matrix holds distances). Were you asking for someone to re-write this so that it calculates the cost of all permutations? – Tibrogargan Apr 20 '17 at 21:37
  • @Tibrogargan I believe I could do it if pointed in the direction. "A, B, C, ...etc" comes from the output I was asked to provide. So I have to create those, and was hoping someone who understand TSP would have a good grasp on exactly what. I have figured out how to do the cost based on minDistance and weight. It is a matrice so I am assuming it is distance between cities. Each city I'm assuming would be A, B, C. Sorry for any misunderstanding, I will try and reword it to be more concise. – Girls.Gone.Wired Apr 20 '17 at 22:34
  • @Tibrogargan I would suffice without the A, B, C and just the permutations, and which is the fastest root. http://www.sanfoundry.com/java-program-implement-traveling-salesman-problem-using-nearest-neighbour-algorithm/ is an output type I am looking for. Instead of "A, B, C" I would be happy with "1, 2, 4, 3, 6, 4" etc. – Girls.Gone.Wired Apr 20 '17 at 22:37
  • You could actually do all permutations with the code you have now by passing the start city index into the `tsp()` function instead of hard coding it to `1`. There's more efficient ways, but that would work. (BTW, any particular reason you using not using zero based indexes?) – Tibrogargan Apr 20 '17 at 22:40

0 Answers0