/* * Adds the next edge in the path. * This is probabilitically determined based on edge weight. * The better the edge weight, the more likely it will be chosen. */ private void TakeNextEdge(Ant ant) { int currentCity = ant.Path[ant.Count - 1]; //Compile list of cities that the ant has NOT visited. List <int> citiesNotVisited = new List <int>(); for (int i = 0; i < Cities.Length; i++) { if (!ant.AlreadyVisited(i) && distances[currentCity, i] != double.PositiveInfinity) { citiesNotVisited.Add(i); } } if (citiesNotVisited.Count > 0) { double rowWeight = RowWeight(currentCity, citiesNotVisited); int maxIndex = 0; double max = 0; List <double> probabilities = new List <double>(); for (int i = 0; i < citiesNotVisited.Count; i++) { probabilities.Add(EdgeWeight(currentCity, citiesNotVisited[i]) / rowWeight); if (probabilities[i] > max) { max = probabilities[i]; maxIndex = i; } } double bestEdgeRandom = random.NextDouble(); if (bestEdgeRandom < SELECT_BEST_PROBABILITY) { ant.Add(citiesNotVisited[maxIndex]); } else { double rand = random.NextDouble(); for (int i = 0; i < probabilities.Count; i++) { if (rand <= probabilities[i]) { ant.Add(citiesNotVisited[i]); return; } rand -= probabilities[i]; } } } else { ResetAnt(ant); } }
/* * Clears out the ant's path. * The ant's new path is then started at a random city. */ private void ResetAnt(Ant ant) { ant.Path.Clear(); ant.Visited.Clear(); ant.Add(random.Next(0, Cities.Length)); }