private void Crossover(Tour parent1, Tour parent2, Tour child) { int unique = 0; child.Clear(); int index = 0; int start = rand.Next(0, numberOfCities * 6 / 10); int len = rand.Next(numberOfCities * 3 / 10, (numberOfCities - 1 - start)); List <int> S; S = parent1.GetRange(start, len); int i = 0; while (index < start) { if (!S.Contains(parent2[i])) { child.Add(parent2[i]); index++; } else { unique++; } i++; } child.AddRange(S); index += len; while (index < parent1.Count()) { if (!S.Contains(parent2[i])) { unique++; child.Add(parent2[i]); index++; } else { unique++; } i++; } if (unique == numberOfCities - len) { Mutate(child); } }
private void btnStart_Click(object sender, EventArgs e) { Stopwatch stopwatch = new Stopwatch(); if (btnStart.Text.Equals("Start")) { btnStart.Text = "Stop"; gaThreadCancellationToken = new CancellationTokenSource(); populationSize = Convert.ToInt32(numPop.Value); iterations = Convert.ToInt32(numGeneration.Value); MUTATION_PROBABILITY = Convert.ToInt32(numMutate.Value); int duplicatesTimer = 0; stopwatch.Start(); Task tMain = Task.Run(() => { globalTour.Clear(); tourPopulation.Clear(); globalTourLength = Double.MaxValue; Populate(); CalculateCostAllToursInPolulation(); tourPopulation.Sort(); for (int k = 0; k < iterations; k++) { duplicatesTimer++; if (gaThreadCancellationToken.IsCancellationRequested) { break; } SimulateGeneration(); CalculateCostAllToursInPolulation(); tourPopulation.Sort(); if (globalTourLength > tourPopulation[0].GetDistance()) { Tour Changed = findReplacement(tourPopulation[0], globalTour); globalTour = tourPopulation[0]; globalTourLength = tourPopulation[0].GetDistance(); DrawTour(Changed); drawnTourLengthLabel.BeginInvoke(new MethodInvoker(() => { drawnTourLengthLabel.Text = "Drawn tour length: " + globalTourLength; })); labelLastSolution.BeginInvoke(new MethodInvoker(() => { labelLastSolution.Text = "Best solution found @: " + k; })); } iterationLabel.BeginInvoke(new MethodInvoker(() => { iterationLabel.Text = "Iteration: " + k; })); if (duplicatesTimer > duplicatesRemovalInterval) { duplicatesTimer = 0; Tour Prev = tourPopulation[0]; Tour Next; for (int i = 1; i < tourPopulation.Count; i++) { Next = tourPopulation[i]; if (Prev.GetDistance() == Next.GetDistance()) { if (Prev.Hash() == Next.Hash()) { Mutate(tourPopulation[i]); } else { Prev = Next; } } else { Prev = Next; } } CalculateCostAllToursInPolulation(); tourPopulation.Sort(); } } btnStart.BeginInvoke(new MethodInvoker(() => { btnStart.Text = "Start"; })); }, gaThreadCancellationToken.Token); } else { gaThreadCancellationToken.Cancel(); } }