// 对parent1和parent2进行交叉操作,生成新的 tour 路径 public static Tour crossover(Tour parent1, Tour parent2) { // Create new child tour Tour child = new Tour(parent1.tourSize()); // startPos endPos之间的序列,会被遗传到下一代。 (如果startPos<endPos,就是取反) int startPos = (int)(new Random().NextDouble() * parent1.tourSize()); int endPos = (int)(new Random().NextDouble() * parent1.tourSize()); // Loop and add the sub tour from parent1 to our child for (int i = 0; i < child.tourSize(); i++) { // If our start position is less than the end position if (startPos < endPos && i > startPos && i < endPos) { child.setCity(i, parent1.getCity(i)); } // If our start position is larger else if (startPos > endPos) { if (!(i < startPos && i > endPos)) { child.setCity(i, parent1.getCity(i)); } } } // 由于child已经继承了parent1的部分city. 下面就是找 parent2中还被child继承的那些city // 要保证city的唯一性 for (int i = 0; i < parent2.tourSize(); i++) { // If child doesn't have the city add it if (!child.containsCity(parent2.getCity(i))) { // Loop to find a spare position in the child's tour for (int ii = 0; ii < child.tourSize(); ii++) { // Spare position found, add city if (child.getCity(ii) == null) { child.setCity(ii, parent2.getCity(i)); break; } } } } return(child); }
// 突变操作。随机交换 private static void mutate(Tour tour) { // Loop through tour cities for (int tourPos1 = 0; tourPos1 < tour.tourSize(); tourPos1++) { // Apply mutation rate if (new Random().NextDouble() < mutationRate) { // Get a second random position in the tour int tourPos2 = (int)(tour.tourSize() * new Random().NextDouble()); // Get the cities at target position in tour City city1 = tour.getCity(tourPos1); City city2 = tour.getCity(tourPos2); // Swap them around tour.setCity(tourPos2, city1); tour.setCity(tourPos1, city2); } } }