// Order Crossover public void CrossChromosomeWithParents(Chromosome Parent1, Chromosome Parent2, int startingNode, int endingNode) { clearRoute(); // Randomly get the part of Parent1 that will be transferred to Child int start = startingNode; int end = endingNode; // Copy selected part of Parent1 to Child for (int i = start; i <= end; i++) { Nodes[i] = Parent1.Nodes[i]; } // Sweep Parent2 circularly and copy remaining nodes int childIndex = (end + 1 == Nodes.Length) ? 0 : end + 1; int parentIndex = childIndex; while (childIndex != start) { bool assignedNode = false; int parentStartingIndex = parentIndex; do { int parentNode = Parent2.Nodes[parentIndex]; if (isNodePresent(parentNode)) { parentIndex = (parentIndex + 1 == Nodes.Length) ? 0 : parentIndex + 1; // Check to avoid infinite loop. // Generally, if it gets here, then the whole chromosome will get messed up anyway. if (parentIndex == parentStartingIndex) { //Nodes[childIndex] = -1; assignedNode = true; } } else { Nodes[childIndex] = parentNode; assignedNode = true; } } while (!assignedNode); childIndex = (childIndex + 1 == Nodes.Length) ? 0 : childIndex + 1; } }
public void RunSimulation(Map map) { // Get number of clients on the map (without depo) int numberOfClients = map.Locations.Count - 1; // Get max possible value based on due date of depo // Double maxValue = Convert.ToDouble(map.Locations.First().DueDate); // Set an absurdly high maxValue Double maxValue = 8000; // Set min possible value as 1.0 - impossible to achieve, but not illegal. Double minValue = 1.0; // Generate random initial chromosomes for (int i = 0; i < PopulationSize; i++) { /*Solutions[i] = new Chromosome(numberOfClients); do { Solutions[i].MakeRandomChromosome(); Solutions[i].FitnessFunction(map); } while (Solutions[i].Fitness < 0);*/ Chromosome c = new Chromosome(numberOfClients); do { c.MakeRandomChromosome(); c.Fitness = c.FitnessFunction(map); } while (c.Fitness < 0); Solutions.Add(c); } for (int i = 0; i < Generations; i++) { Solutions = geneticRoulette.createNewGeneration(Solutions, maxValue, minValue, map); if (checkStopConditions() == true) break; //Chromosome ch = GetBestSolutionFound(); //Console.WriteLine("best " + ch.FitnessFunction(map) + ", routes " + ch.Routes.Count()); } }