// Mutate a tour using swap mutation private static void mutate(Knapsack sac) { Random rnd = new Random(); // Loop through tour cities for (int i = 0; i < sac.getObjects().Length; i++) { // Apply mutation rate if (rnd.NextDouble() < mutationRate) { // Get a second random position in the tour int mutationPos = (int)(sac.getObjects().Length *rnd.NextDouble()); if (sac.getObjects()[mutationPos]) { sac.setoneObject(i, false); sac.processValue(); sac.processWeight(); } else { if (sac.getWeight() + MainForm.listItems[i].Weight <= sac.getCapacity()) { sac.setoneObject(i, true); sac.processValue(); sac.processWeight(); } } } } }
// Applies crossover to a set of parents and creates offspring public static Knapsack crossover(Knapsack parent1, Knapsack parent2) { Random rnd = new Random(); // Create new child tour Knapsack child = new Knapsack(); // Get start and end sub tour positions for parent1's tour int crossPos = (int)(rnd.NextDouble() * parent1.getObjects().Length); // Loop and add the sub tour from parent1 to our child for (int i = 0; i < child.getObjects().Length; i++) { if (i < crossPos) { child.processWeight(); if (child.getWeight() + MainForm.listItems[i].Weight <= child.getCapacity()) { child.setoneObject(i, parent2.getoneObject(i)); child.processWeight(); } } else { child.processWeight(); if (child.getWeight() + MainForm.listItems[i].Weight <= child.getCapacity()) { child.setoneObject(i, parent1.getoneObject(i)); child.processWeight(); } } } child.processValue(); return(child); }