Guest User

JAVA

a guest
Dec 18th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 21.16 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.util.*;
  7.  
  8. public class Main {
  9.  
  10.     public static void main(String[] args) {
  11.  
  12.         //region variables
  13.         // iteration variables
  14.         int i, j, g;
  15.  
  16.         //main variables
  17.         int[][] population, arrayOfDistance;
  18.         int numberOfCities, numberOfSubjects = 40, numberOfLoopTimes = 100000, numberOfGroupMemberOfTournament = 4, numberOfFinal = 1;
  19.         int pmxProbability = 80, inversionMutationProbability = 5, swapMutationProbability = 993;
  20.  
  21.         //various additional variables
  22.         Boolean whichSelection = true; //true - tournament, false - roulette
  23.         Scanner s = null; //variable to scan file
  24.         String line; //variable to readLine
  25.         String[] lineArray; //array variable to line.split
  26.         Random rnd = new Random();
  27.         long startTime, stopTime;
  28.  
  29.         //file variable
  30.         File file = new File("berlin52.txt");
  31.         // URL url = new URL("http://elib.zib.de/pub/mp-testdata/tsp/tsplib/tsp/berlin52.tsp");
  32.  
  33.         //endregion
  34.  
  35.         //region checking if file exists
  36.         {
  37.             if (!file.exists()) {
  38.                 System.out.println("There is no file with name: '" + file.getName() + "'.");
  39.                 return;
  40.             }
  41.         }
  42.         //endregion
  43.  
  44.         //region main program
  45.         for (int z = 0; z < numberOfFinal; z++) {
  46.             startTime = System.currentTimeMillis();
  47.             try {
  48.                 //region open a file
  49.                 //s = new Scanner(url.openStream());
  50.                 s = new Scanner(file);
  51.                 line = s.nextLine();
  52.                 numberOfCities = Integer.parseInt(line);
  53.                 arrayOfDistance = new int[numberOfCities][numberOfCities];
  54.  
  55.                 for (i = 0; i < numberOfCities; i++) {
  56.                     line = s.nextLine();
  57.                     lineArray = line.split(" ");
  58.                     for (j = 0; j < lineArray.length; j++) {
  59.                         arrayOfDistance[i][j] = Integer.parseInt(lineArray[j]);
  60.                         arrayOfDistance[j][i] = Integer.parseInt(lineArray[j]);
  61.                     }
  62.                 }
  63.                 //endregion
  64.  
  65.                 //region creating a population
  66.                 population = createPopulation(numberOfCities, numberOfSubjects);
  67.                 //endregion
  68.  
  69.                 System.out.println("Calculating...");
  70.  
  71.                 //region tournament/roulette + crossing + mutation
  72.                 for (g = 0; g < numberOfLoopTimes; g++) {
  73.                     //region tournament or roulette
  74.                     int[] bestSubjectsIndex = new int[population.length];
  75.  
  76.                     if (whichSelection) {
  77.  
  78.                         //region tournament
  79.                         int[] tournamentSubjectGroup = new int[numberOfGroupMemberOfTournament];
  80.                         int minSubjectIndex, minSubjectLength;
  81.  
  82.                         for (i = 0; i < population.length; i++) {
  83.                             tournamentSubjectGroup = returnOneTournamentGroup(numberOfSubjects, numberOfGroupMemberOfTournament);
  84.                             minSubjectIndex = -1;
  85.                             minSubjectLength = Integer.MAX_VALUE;
  86.                             for (j = 0; j < tournamentSubjectGroup.length; j++) {
  87.                                 if (returnOneSubjectLength(population[tournamentSubjectGroup[j]], arrayOfDistance) < minSubjectLength) {
  88.                                     minSubjectLength = returnOneSubjectLength(population[tournamentSubjectGroup[j]], arrayOfDistance);
  89.                                     minSubjectIndex = tournamentSubjectGroup[j];
  90.                                 }
  91.                             }
  92.                             bestSubjectsIndex[i] = minSubjectIndex;
  93.                         }
  94.  
  95.  
  96.                         //endregion
  97.  
  98.                         //region print best subject after tournament
  99. //                    for (int x = 0; x < population.length; x++) {
  100. //                        printOneSubject(population, bestSubjectsIndex[x]);
  101. //                    }
  102. //                    System.out.println();
  103.                         //endregion
  104.  
  105.                     } else {
  106.  
  107.                         //region roulette
  108.                         int worstSubjectLength = returnWorstSubjectLength(population, arrayOfDistance);
  109.                         int[] subjectsGrades = new int[population.length];
  110.                         int sumOfAllGrades = 0, tempSum, tempIndex, randomNumberForGrade;
  111.                         for (i = 0; i < population.length; i++) {
  112.                             subjectsGrades[i] = worstSubjectLength + 1 - returnOneSubjectLength(population[i], arrayOfDistance);
  113.                             sumOfAllGrades += subjectsGrades[i];
  114.                         }
  115.  
  116.                         for (i = 0; i < bestSubjectsIndex.length; i++) {
  117.                             randomNumberForGrade = rnd.nextInt(sumOfAllGrades);
  118.                             tempSum = 0;
  119.                             tempIndex = 0;
  120.                             tempSum += subjectsGrades[tempIndex];
  121.                             while (tempSum <= randomNumberForGrade) {
  122.                                 tempIndex++;
  123.                                 tempSum += subjectsGrades[tempIndex];
  124.                             }
  125.                             bestSubjectsIndex[i] = tempIndex;
  126.                         }
  127.  
  128.                         //endregion
  129.  
  130.                         //region print best subject after roulette
  131. //                    for (int x = 0; x < population.length; x++) {
  132. //                        printOneSubject(population, bestSubjectsIndex[x]);
  133. //                    }
  134. //                    System.out.println();
  135.                         //endregion
  136.  
  137.                     }
  138.                     //endregion
  139.  
  140.                     //region update population
  141.                     int[][] tempPopulation = new int[numberOfSubjects][numberOfCities];
  142.                     for (i = 0; i < tempPopulation.length; i++) {
  143.                         for (j = 0; j < tempPopulation[i].length; j++) {
  144.                             tempPopulation[i][j] = population[bestSubjectsIndex[i]][j];
  145.                         }
  146.                     }
  147.                     population = returnArray1toArray2(tempPopulation);
  148.                     //endregion
  149.  
  150.                     //region crossing
  151.                     int startRandomPMX, stopRandomPMX, tempCityPMX, tempIndexPMX;
  152.                     int[] childX1 = new int[numberOfCities], childX2 = new int[numberOfCities];
  153.  
  154.                     if (rnd.nextInt(100) < pmxProbability) {
  155.                         for (i = 0; i < population.length; i += 2) {
  156.                             startRandomPMX = rnd.nextInt(numberOfCities);
  157.                             stopRandomPMX = rnd.nextInt(numberOfCities - startRandomPMX) + startRandomPMX;
  158.  
  159.                             //region fill childs with -1
  160.                             Arrays.fill(childX1, -1);
  161.                             Arrays.fill(childX2, -1);
  162.                             //endregion
  163.  
  164.                             //region fill random range with original value of population
  165.                             for (j = startRandomPMX; j <= stopRandomPMX; j++) {
  166.                                 childX1[j] = population[i][j];
  167.                                 childX2[j] = population[i + 1][j];
  168.                             }
  169.                             //endregion
  170.  
  171.                             //region child 1
  172.  
  173.                             //region from 0 to start
  174.                             for (j = 0; j < startRandomPMX; j++) {
  175.                                 tempCityPMX = population[i + 1][j];
  176.                                 tempIndexPMX = returnIndex(childX1, tempCityPMX);
  177.                                 while (tempIndexPMX != -1) {
  178.                                     tempCityPMX = population[i + 1][tempIndexPMX];
  179.                                     tempIndexPMX = returnIndex(childX1, tempCityPMX);
  180.                                 }
  181.                                 childX1[j] = tempCityPMX;
  182.                             }
  183.                             //endregion
  184.  
  185.                             //region from stop to end
  186.                             for (j = stopRandomPMX + 1; j < childX1.length; j++) {
  187.                                 tempCityPMX = population[i + 1][j];
  188.                                 tempIndexPMX = returnIndex(childX1, tempCityPMX);
  189.                                 while (tempIndexPMX != -1) {
  190.                                     tempCityPMX = population[i + 1][tempIndexPMX];
  191.                                     tempIndexPMX = returnIndex(childX1, tempCityPMX);
  192.                                 }
  193.                                 childX1[j] = tempCityPMX;
  194.                             }
  195.                             //endregion
  196.  
  197.                             //endregion
  198.  
  199.                             //region child 2
  200.  
  201.                             //region from 0 to start
  202.                             for (j = 0; j < startRandomPMX; j++) {
  203.                                 tempCityPMX = population[i][j];
  204.                                 tempIndexPMX = returnIndex(childX2, tempCityPMX);
  205.                                 while (tempIndexPMX != -1) {
  206.                                     tempCityPMX = population[i][tempIndexPMX];
  207.                                     tempIndexPMX = returnIndex(childX2, tempCityPMX);
  208.                                 }
  209.                                 childX2[j] = tempCityPMX;
  210.                             }
  211.                             //endregion
  212.  
  213.                             //region from stop to end
  214.                             for (j = stopRandomPMX + 1; j < childX1.length; j++) {
  215.                                 tempCityPMX = population[i][j];
  216.                                 tempIndexPMX = returnIndex(childX2, tempCityPMX);
  217.                                 while (tempIndexPMX != -1) {
  218.                                     tempCityPMX = population[i][tempIndexPMX];
  219.                                     tempIndexPMX = returnIndex(childX2, tempCityPMX);
  220.                                 }
  221.                                 childX2[j] = tempCityPMX;
  222.                             }
  223.                             //endregion
  224.  
  225.                             //endregion
  226.  
  227.                             //region update population
  228.                             for (j = 0; j < population[i].length; j++) {
  229.                                 population[i][j] = childX1[j];
  230.                                 population[i + 1][j] = childX2[j];
  231.                             }
  232.                             //endregion
  233.  
  234.                         }
  235.                     }
  236.                     //endregion
  237.  
  238.                     //region mutation inverse
  239.                     int chanceOfMutation, startMutation, stopMutation;
  240.                     for (i = 0; i < population.length; i++) {
  241.                         chanceOfMutation = rnd.nextInt(100);
  242.                         if (chanceOfMutation < inversionMutationProbability) {
  243.                             startMutation = rnd.nextInt(population[i].length);
  244.                             stopMutation = rnd.nextInt(population[i].length - startMutation) + startMutation;
  245.                             int[] tempArray = new int[stopMutation - startMutation];
  246.                             for (j = 0; j < tempArray.length; j++) {
  247.                                 tempArray[j] = population[i][startMutation + j];
  248.                             }
  249.                             tempArray = reverseArray(tempArray);
  250.                             for (j = 0; j < tempArray.length; j++) {
  251.                                 population[i][startMutation + j] = tempArray[j];
  252.                             }
  253.                         }
  254.                     }
  255.                     //endregion
  256.  
  257.                     //region mutation swap
  258. //                    int chanceOfMutation, tempCityMutation, tempRandomCityMutation;
  259. //                    for (i = 0; i < population.length; i++) {
  260. //                        for (j = 0; j < population[i].length; j++) {
  261. //                            chanceOfMutation = rnd.nextInt(1000);
  262. //                            if (chanceOfMutation > swapMutationProbability) {
  263. //                                tempRandomCityMutation = rnd.nextInt(population[i].length);
  264. //                                while (tempRandomCityMutation == j) {
  265. //                                    tempRandomCityMutation = rnd.nextInt(population[i].length);
  266. //                                }
  267. //                                tempCityMutation = population[i][j];
  268. //                                population[i][j] = population[i][tempRandomCityMutation];
  269. //                                population[i][tempRandomCityMutation] = tempCityMutation;
  270. //                            }
  271. //                        }
  272. //                    }
  273.                     //endregion
  274.                 }
  275.                 //endregion
  276.  
  277.                 printBestSubjectLength(population, arrayOfDistance);
  278.  
  279.                 printToFile(population,arrayOfDistance, "wynik.txt");
  280.                 //printWorstSubjectLength(population, arrayOfDistance);
  281.             } catch (IOException io) {
  282.                 System.out.println("blad bliku");
  283.             } finally {
  284.                 if (s != null)
  285.                     s.close();
  286.             }
  287.             stopTime = System.currentTimeMillis();
  288.             System.out.printf("Time: %6d", (stopTime-startTime));
  289.             System.out.println();
  290.         }
  291.         //endregion
  292.     }
  293.  
  294.     //return statement methods
  295.     private static int[][] createPopulation(int tempNumberOfCities, int tempNrSubjects) {
  296.         //creating population
  297.         int[][] tempPopulation = new int[tempNrSubjects][tempNumberOfCities];
  298.         Random rnd = new Random();
  299.         int j, tempRandomSubject;
  300.         List<Integer> tempCities = new ArrayList<Integer>();
  301.         for (int i = 0; i < tempNrSubjects; i++) {
  302.             for (j = 0; j < tempNumberOfCities; j++)
  303.                 tempCities.add(j);
  304.             for (j = 0; j < tempNumberOfCities; j++) {
  305.                 tempRandomSubject = rnd.nextInt(tempCities.size());
  306.                 tempPopulation[i][j] = tempCities.get(tempRandomSubject);
  307.                 tempCities.remove(tempRandomSubject);
  308.             }
  309.         }
  310.         return tempPopulation;
  311.  
  312. //        for (int i = 0; i < nrSubjects; i++) {
  313. //            for (j = 0; j < nrCities; j++)
  314. //                subjectBoolean[i] = true;
  315. //            for (j = 0; j < nrCities; j++) {
  316. //                randomSubject=rnd.nextInt(nrCities);
  317. //                if (subjectBoolean[randomSubject]) {
  318. //                    population[i][j] = randomSubject;
  319. //                    subjectBoolean[randomSubject] = false;
  320. //                } else {
  321. //                    do {
  322. //                        randomSubject = rnd.nextInt(nrCities);
  323. //                    } while (!subjectBoolean[randomSubject]);
  324. //                    population[i][j] = randomSubject;
  325. //                    subjectBoolean[randomSubject] = false;
  326. //                }
  327. //
  328. //            }
  329. //        }
  330.  
  331.     }
  332.  
  333.     private static int returnOneSubjectLength(int[] tempSubject, int[][] tempArrayOfDistance) {
  334.         int tempSubjectLength = 0;
  335.         for (int j = 0; j < tempSubject.length - 1; j++) {
  336.             tempSubjectLength += tempArrayOfDistance[tempSubject[j]][tempSubject[j + 1]];
  337.         }
  338.         tempSubjectLength += tempArrayOfDistance[tempSubject[0]][tempSubject[tempSubject.length - 1]];
  339.         return tempSubjectLength;
  340.     }
  341.  
  342.     private static int returnBestSubjectLength(int[][] tempPopulation, int[][] tempArrayOfDistance) {
  343.         int tempBestSubjectLength = Integer.MAX_VALUE;
  344.         for (int i = 0; i < tempPopulation.length; i++) {
  345.             if (returnOneSubjectLength(tempPopulation[i], tempArrayOfDistance) < tempBestSubjectLength)
  346.                 tempBestSubjectLength = returnOneSubjectLength(tempPopulation[i], tempArrayOfDistance);
  347.         }
  348.         return tempBestSubjectLength;
  349.     }
  350.  
  351.     private static int returnWorstSubjectLength(int[][] tempPopulation, int[][] tempArrayOfDistance) {
  352.         int tempWorstSubjectLength = Integer.MIN_VALUE;
  353.         for (int i = 0; i < tempPopulation.length; i++) {
  354.             if (returnOneSubjectLength(tempPopulation[i], tempArrayOfDistance) > tempWorstSubjectLength)
  355.                 tempWorstSubjectLength = returnOneSubjectLength(tempPopulation[i], tempArrayOfDistance);
  356.         }
  357.         return tempWorstSubjectLength;
  358.     }
  359.  
  360.     private static int[] returnOneTournamentGroup(int tempNumberOfSubjects, int tempNumberOfTournamentGroupMember) {
  361.         int[] tempGroup = new int[tempNumberOfTournamentGroupMember];
  362.         int tempRandomSubject;
  363.         Random rnd = new Random();
  364.         List<Integer> tempSubjects = new ArrayList<Integer>();
  365.  
  366.         for (int j = 0; j < tempNumberOfSubjects; j++)
  367.             tempSubjects.add(j);
  368.         for (int j = 0; j < tempNumberOfTournamentGroupMember; j++) {
  369.             tempRandomSubject = rnd.nextInt(tempSubjects.size());
  370.             tempGroup[j] = tempSubjects.get(tempRandomSubject);
  371.             tempSubjects.remove(tempRandomSubject);
  372.         }
  373.         return tempGroup;
  374.     }
  375.  
  376.     private static int returnIndex(int[] tempChild, int tempCity) {
  377.         for (int i = 0; i < tempChild.length; i++)
  378.             if (tempChild[i] == tempCity) return i;
  379.         return -1;
  380.     }
  381.  
  382.     private static int[][] returnArray1toArray2(int[][] tempArray) {
  383.         int[][] tempFinalArray = new int[tempArray.length][tempArray[0].length];
  384.         for (int i = 0; i < tempArray.length; i++) {
  385.             for (int j = 0; j < tempArray[i].length; j++) {
  386.                 tempFinalArray[i][j] = tempArray[i][j];
  387.             }
  388.         }
  389.         return tempFinalArray;
  390.     }
  391.  
  392.     private static int[] reverseArray(int[] tempArray) {
  393.         int[] tempReverseArray = new int[tempArray.length];
  394.         for (int i = 0; i < tempArray.length / 2; i++) {
  395.             int temp = tempArray[i];
  396.             tempArray[i] = tempArray[tempArray.length - i - 1];
  397.             tempArray[tempArray.length - i - 1] = temp;
  398.         }
  399.         for (int i = 0; i < tempArray.length; i++) {
  400.             tempReverseArray[i] = tempArray[i];
  401.         }
  402.         return tempReverseArray;
  403.     }
  404.  
  405.     //print methods
  406.     private static void printOneDimensionArray(int[] tempArray, Boolean oneLine) {
  407.         //printing array with formatting
  408.         for (int i = 0; i < tempArray.length; i++) {
  409.             System.out.printf("%6d", tempArray[i]);
  410.             if (!oneLine) System.out.println();
  411.         }
  412.         System.out.println();
  413.     }
  414.  
  415.     private static void printTwoDimensionArray(int[][] tempArray) {
  416.         //printing array with formatting
  417.         for (int i = 0; i < tempArray.length; i++) {
  418.             for (int j = 0; j < tempArray[i].length; j++) {
  419.                 System.out.printf("%6d", tempArray[i][j]);
  420.             }
  421.             System.out.println();
  422.         }
  423.         System.out.println();
  424.     }  // print all subjects
  425.  
  426.     private static void printOneSubject(int[][] tempPopulation, int tempIndex) {
  427.  
  428.         for (int i = 0; i < tempPopulation[tempIndex].length; i++) {
  429.             System.out.printf("%6d", tempPopulation[tempIndex][i]);
  430.         }
  431.         System.out.println();
  432.     }
  433.  
  434.     private static void printOneSubjectLength(int[] tempSubject, int[][] tempArrayOfDistance) {
  435.         System.out.println("Length of the subject: " + returnOneSubjectLength(tempSubject, tempArrayOfDistance));
  436.         System.out.println();
  437.     }
  438.  
  439.     private static void printSubjectsLength(int[][] tempPopulation, int[][] tempArrayOfDistance) {
  440.         for (int i = 0; i < tempPopulation.length; i++) {
  441.             System.out.println(i + ". " + returnOneSubjectLength(tempPopulation[i], tempArrayOfDistance));
  442.         }
  443.         System.out.println();
  444.     }
  445.  
  446.     private static void printBestSubjectLength(int[][] tempPopulation, int[][] tempArrayOfDistance) {
  447.         System.out.println("Best subject length: " + returnBestSubjectLength(tempPopulation, tempArrayOfDistance));
  448.     }
  449.  
  450.     private static void printWorstSubjectLength(int[][] tempPopulation, int[][] tempArrayOfDistance) {
  451.         System.out.println("Worst subject length: " + returnWorstSubjectLength(tempPopulation, tempArrayOfDistance));
  452.     }
  453.  
  454.     private static void printToFile(int[][] tempPopulation, int[][] tempArrayOfDistance, String fileName) {
  455.         PrintWriter tempFile = null;
  456.         try {
  457.             tempFile = new PrintWriter(fileName);
  458.             for (int i = 0; i < tempPopulation.length; i++) {
  459.                 for (int j = 0; j < tempPopulation[i].length; j++) {
  460.                     if (j == (tempPopulation[i].length - 1))
  461.                         tempFile.printf("%d", tempPopulation[i][j]);
  462.                     else
  463.                         tempFile.printf("%d-", tempPopulation[i][j]);
  464.  
  465.                 }
  466.                 tempFile.println(" " + returnOneSubjectLength(tempPopulation[i], tempArrayOfDistance));
  467.             }
  468.         } catch (IOException io) {
  469.             System.out.println("blad");
  470.         } finally {
  471.             if (tempFile != null)
  472.                 tempFile.close();
  473.         }
  474.     }
  475.  
  476.  
  477.  
  478. }
Add Comment
Please, Sign In to add comment