Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.37 KB | None | 0 0
  1. package tspCopy;
  2. import java.io.*;
  3. import java.util.*;
  4. import java.sql.*;
  5. import java.util.Scanner;
  6. public class tsp {
  7.  
  8. static double[][] distances;
  9.  
  10. public static void main(String args[]) {
  11.  
  12. /* Variables to store data. */
  13. ArrayList<Town> towns = new ArrayList<Town>();
  14.  
  15. /* Read all towns and store in data structure. */
  16. /*try {
  17. File file = new File("C:/Users/Silvio/Desktop/MAD/monumenti.txt");
  18. FileReader fileReader = new FileReader(file);
  19. BufferedReader bufferedReader = new BufferedReader(fileReader);
  20.  
  21. String line;
  22.  
  23. while ((line = bufferedReader.readLine()) != null) {
  24.  
  25. // Get the data from each line.
  26. String[] data = line.split(",");
  27.  
  28. int id = Integer.parseInt(data[0]) - 1; // Minus one as IDs start from 1. Plus 1 while printing.
  29. String name = data[1];
  30. double x = Double.parseDouble(data[2]);
  31. double y = Double.parseDouble(data[3]);
  32.  
  33. // Store all the data as an object and store in arrayList.
  34. Town newTown = new Town(id, name, x, y);
  35. towns.add(newTown);
  36.  
  37. }
  38.  
  39. fileReader.close();
  40.  
  41. } catch (IOException e) {
  42. e.printStackTrace();
  43. }*/
  44.  
  45. //connessione con il database
  46. try {
  47. Connection myConn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/db.triplan?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "root");
  48.  
  49. Statement myStmt = myConn.createStatement();
  50.  
  51. ResultSet myRs = myStmt.executeQuery("SELECT * FROM places;");
  52. System.out.print("Inserisci id citta:\n");
  53. Scanner input = new Scanner(System.in);
  54. int s_city = input.nextInt();
  55. input.close();
  56. int count = 0;
  57. while(myRs.next()) {
  58. if(myRs.getInt("city_idcity")==s_city) {
  59. System.out.println(count+1+","+ myRs.getString("name_places"));
  60. int id = count;
  61. String name = myRs.getString("name_places");
  62. double x = myRs.getDouble("latitude");
  63. double y = myRs.getDouble("longitude");
  64. Town newTown = new Town(id, name, x, y);
  65. towns.add(newTown);
  66. count++;
  67. }
  68. System.out.print("Inserisci id monumento di partenza:\n");
  69. Scanner input1 = new Scanner(System.in);
  70. int s_monument = input.nextInt();
  71. input.close();
  72. //input.close();
  73. }
  74. }catch(Exception exc) {
  75. exc.printStackTrace();
  76. }
  77.  
  78.  
  79. /* Find the distance between all the towns. Store results in a 2D array for reuse. */
  80. distances = new double[towns.size()][towns.size()];
  81.  
  82. for(Town a : towns) {
  83. for(Town b : towns) {
  84. if(a.id==b.id) { // If a & b are the same town.
  85. distances[a.id][b.id] = 0;
  86. continue;
  87. }else {
  88. distances[a.id][b.id] = a.distanceTo(b); }
  89.  
  90. // Find and store the distance between towns.
  91.  
  92. }
  93. }
  94.  
  95.  
  96.  
  97. /* Calculate all the possible solutions for the shortest route. */
  98.  
  99. double bestDistance = 0.0;
  100. ArrayList<Integer> bestSquence = new ArrayList<Integer>();
  101. ArrayList<Integer> visitSequence = new ArrayList<Integer>();
  102.  
  103. // For selecting starting point. Try everything as a starting point.
  104. System.out.print("Inserisci id monumento di partenza:\n");
  105. Scanner input1 = new Scanner(System.in);
  106. int s_monument = input1.nextInt();
  107. input1.close();
  108. visitSequence.add(s_monument);
  109. for(Town t : towns){
  110. if(s_monument == t.id){
  111. /* Copy town's arrayList and use it to remove visited towns. */
  112. ArrayList<Town> toVisit = new ArrayList<Town>(towns);
  113. removeTown(t.id, toVisit); // Remove the starting town.
  114.  
  115. /* Nearest neighbour algorithm. */
  116.  
  117. double totalDistance = 0.0;
  118. //visitSequence.add(s_town);
  119. visitSequence.add((t.id+1)); // Save the visiting sequence as a string.
  120.  
  121. int currentTownID = t.id;
  122. while(!toVisit.isEmpty()) { // Till we have visited all the towns.
  123.  
  124. int nearestTownID = nearestTown(currentTownID, toVisit);
  125.  
  126. visitSequence.add(nearestTownID+1); // Add to sequence. Plus 1 to get actual ID.
  127. totalDistance += distances[currentTownID][nearestTownID]; // Add the distance visited.
  128.  
  129. removeTown(nearestTownID, toVisit); // Visit the nearest town.
  130. currentTownID = nearestTownID; // We are now in that town.
  131. }
  132.  
  133.  
  134. // If first time OR if current result is better.
  135. if(bestDistance == 0.0 || totalDistance < bestDistance) {
  136. bestDistance = totalDistance;
  137. bestSquence = visitSequence;
  138. }
  139.  
  140. // System.out.println("Starting town: " + t.name + ". Travelled Distance: " + totalDistance);
  141.  
  142. }
  143.  
  144. }
  145.  
  146. ArrayList<String> al = new ArrayList<String>();
  147. for(int m=0;m<bestSquence.size();m++){
  148. for(Town t1 : towns){
  149. if(t1.id==bestSquence.get(m)){
  150. al.add(t1.name);
  151. break;
  152. }
  153. }
  154. }
  155.  
  156.  
  157. System.out.println("\n\nBest sequence with total distance of " + bestDistance + ":\n\n" + al);
  158.  
  159. }
  160.  
  161.  
  162. /* Method to remove a town from ArrayList<Town>. */
  163. private static void removeTown(int town_id, ArrayList<Town> towns) {
  164.  
  165. // Go through each item in the list till we find the town and remove.
  166. for(int i = 0; i < towns.size(); i++) {
  167. Town current = towns.get(i);
  168.  
  169. if(current.id == town_id) { // Found the town.
  170. towns.remove(i); // Remove from the same array that was passed.
  171. break;
  172. }
  173.  
  174. }
  175. }
  176.  
  177.  
  178. /* Method to find the nearest town from a list of towns that are available to visit. */
  179. private static int nearestTown(int town_id, ArrayList<Town> canVisit) {
  180. int nearestTownID = town_id;
  181. double nearestDistance = 0.0;
  182.  
  183. for(int i = 0; i < distances[town_id].length; i++) {
  184. if(distances[town_id][i] == 0.0) continue; // Skip comparing with same town.
  185.  
  186. // Skip if town ID is not in the list of town that we can visit.
  187. if(!hasTown(i, canVisit)) continue; // Cannot visit this town.
  188.  
  189. // If no value for nearest distance, set this town to be the nearest. (Runs first time).
  190. if(nearestDistance == 0.0) {
  191. nearestTownID = i;
  192. nearestDistance = distances[town_id][i];
  193. continue;
  194. }
  195.  
  196. // Check if current town's distance is shorter.
  197. if(distances[town_id][i] < nearestDistance) {
  198. nearestTownID = i;
  199. nearestDistance = distances[town_id][i];
  200. }
  201. }
  202.  
  203. return nearestTownID;
  204. }
  205.  
  206.  
  207. /* Method to check if a town is in ArrayList<Town>. */
  208. private static boolean hasTown(int town_id, ArrayList<Town> towns) {
  209.  
  210. // Go through each item in the list till we find the town.
  211. for(Town t : towns) {
  212. if(t.id == town_id) { // Found the town.
  213. return true; // Return true.
  214. }
  215. }
  216.  
  217. return false; // Assume that we don't have the town.
  218. }
  219.  
  220.  
  221. /* Method to print out 2D array of doubles. */
  222. public static void printDistances(double[][] array) {
  223. for (double[] arr : array) {
  224. System.out.println(Arrays.toString(arr));
  225. }
  226. }
  227.  
  228. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement