//select random start population private void startpop1() { PresentPopData1.Clear(); NewPopData1.Clear(); genome g = new genome(); for (int i = 0; i < this.cities.Count; i++) { g.order.Add(i); } g.distance = genomefitness(g); g.makestring(); PresentPopData1.Add(g); g = null; g = new genome(); g.distance = 0; if (this.cities.Count % 2 == 0) { for (int i = this.cities.Count / 2; i < this.cities.Count; i++) { g.order.Add(i); } for (int i = (this.cities.Count / 2) - 1; i > -1; i--) { g.order.Add(i); } } else { for (int i = this.cities.Count + 1 / 2; i < this.cities.Count; i++) { g.order.Add(i); } for (int i = (this.cities.Count + 1 / 2) - 1; i > -1; i--) { g.order.Add(i); } } g.makestring(); g.distance = genomefitness(g); PresentPopData1.Add(g); Random m = new Random(); for (int i = 2; i < popsize; i++) { g = new genome(); int[] array = randomarray(m); for (int k = 0; k < this.cities.Count; k++) { g.order.Add(array[k]); } g.distance = genomefitness(g); g.makestring(); PresentPopData1.Add(g); } }
//mutate private genome mutate(genome child) { Random d = new Random(); int num1 = d.Next(0, child.order.Count - 1); int num2 = 0; do { num2 = d.Next(0, child.order.Count - 1); } while (num1 == num2); if (mutaterandom.NextDouble() < mutationrate) { int temp = child.order[num1]; child.order[num1] = child.order[num2]; child.order[num2] = temp; } child.distance = genomefitness(child); child.makestring(); return(child); }