private void Greedy(int firstCity) { Tour tour = new Tour(); List <int> notUsedCities = new List <int>(); double tourLength = 0; for (int i = 0; i < numberOfCities; i++) { notUsedCities.Add(i); } tour.Add(firstCity); notUsedCities.Remove(firstCity); while (notUsedCities.Count > 0) { int actualNodeNumber = tour[tour.Count - 1]; double minLength = Double.MaxValue; int chosenNode = -1; foreach (int nodeNumber in notUsedCities) { double length = distancesBetweenCities[actualNodeNumber, nodeNumber]; if (length < minLength) { minLength = length; chosenNode = nodeNumber; } } tourLength += minLength; tour.Add(chosenNode); notUsedCities.Remove(chosenNode); } tourPopulation.Add(tour); }
private Tour findReplacement(Tour Next, Tour Prev) { Tour B = new Tour(); int k, p; for (int i = 0; i < Prev.Count; i++) { k = Next.IndexOf(Prev[i]); p = k; if (k == numberOfCities - 1) { p = 0; } else { p += 1; } if (i != Next.Count - 1) { if (Next[p] != Prev[i + 1]) { B.Add(Next[p]); } } else { if (Next[p] != Prev[0]) { B.Add(Next[p]); } } } return(B); }
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 Tour generateRandomTour() { Tour tour = new Tour(); List <int> notUsedNodes = new List <int>(); for (int i = 0; i < numberOfCities; i++) { notUsedNodes.Add(i); } for (int i = numberOfCities; i > 0; i--) { int random = rand.Next(i); tour.Add(notUsedNodes[random]); notUsedNodes.RemoveAt(random); } return(tour); }