Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
package file;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 *
 * @author User
 */

    
public class TravelingSalesmanProblem {
    	// there are 17 nodes in example graph (graph is
	// 1-based)

	static int n = 16;
	// give appropriate maximum to avoid overflow

	static int MAX = 1000000;

	// memoization for top down recursion

	
        static int[][] memo = new int[n + 1][1 << (n + 1)];
	static int TSP(int i, int mask, int[][] dist)
	{
            
		// base case
		// if only ith bit and 1st bit is set in our mask,
		// it implies we have visited all other nodes
		// already
		if (mask == ((1 << i) | 3))
			return dist[1][i];
		// memoization
		if (memo[i][mask] != 0)
			return memo[i][mask];

		int res = MAX; // result of this sub-problem

		// we have to travel all nodes j in mask and end the
		// path at ith node so for every node j in mask,
		// recursively calculate cost of travelling all
		// nodes in mask
		// except i and then travel back from node j to node
		// i taking the shortest path take the minimum of
		// all possible j nodes

		for (int j = 1; j <= n; j++)
			if ((mask & (1 << j)) != 0 && j != i && j != 1)
				res = Math.min(res,
							TSP(j, mask & (~(1 << i)),dist)
								+ dist[j][i]);
		return memo[i][mask] = res;
	}

	// Driver program to test above logic


    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
            // all lines in file
            ArrayList<string> lines = new ArrayList();

            BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\User\\Downloads\\testFile.atsp"));

            String line;

            // read lines in file
            while ((line = in.readLine())!=null){
                lines.add(line);
            }

            in.close();
            int size = lines.size();
            // create new 2d array
            int[][] MATRIX = new int[size][];
            boolean first = true;
            // loop through array for each line
            for (int q = 0; q < MATRIX.length; q++)
            {
                // get the rooms by separating by ","
                String[] rooms = lines.get(q).split(",");
                
                if (first) 
                    {
                        first = false;
                        continue;
                    }

                // size 2d array
                MATRIX[q] = new int[rooms.length];

                // loop through and add to array's second dimension
                for (int w = 0; w < rooms.length; w++)
                    {
                        MATRIX[q][w] = Integer.parseInt(rooms[w]);

                    }

                System.out.println(Arrays.toString(MATRIX[q]));
            }

		int ans = MAX;
		for (int i = 1; i <= n; i++)
			// try to go from node 1 visiting all nodes in
			// between to i then return from i taking the
			// shortest route to 1
			ans = Math.min(ans, TSP(i, (1 << (n + 1)) - 1,MATRIX)
									+ MATRIX[i][1]);

		System.out.println(
			"The cost of most efficient tour = " + ans);
	}
}


What I have tried:

this is the matrix that is being read:
0,3,5,48,48,8,
3,0,3,48,48,8,
5,3,0,72,72,48,
48,48,74,0,0,6,
48,48,74,0,0,6,
8,8,50,6,6,0,

the most efficient tour should be 60 but the result is giving me 5
Posted
Updated 29-Oct-22 6:13am
v2

1 solution

Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
Java
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900