|
@@ -1,5 +1,3 @@
|
|
|
-using Microsoft.VisualBasic;
|
|
|
-
|
|
|
namespace AntColony.Algorithm;
|
|
|
|
|
|
/// <summary>
|
|
@@ -71,7 +69,9 @@ public class AntColonyOptimizer
|
|
|
// Каждый муравей строит путь
|
|
|
for (int ant = 0; ant < numberOfAnts; ant++)
|
|
|
{
|
|
|
- var (tour, distance) = ConstructTour();
|
|
|
+ var ct = ConstructTour();
|
|
|
+ if (ct is null) continue;
|
|
|
+ var (tour, distance) = ct.Value;
|
|
|
antTours.Add(tour);
|
|
|
antDistances.Add(distance);
|
|
|
|
|
@@ -98,7 +98,7 @@ public class AntColonyOptimizer
|
|
|
return (bestTourEver, bestDistanceEver);
|
|
|
}
|
|
|
|
|
|
- private (List<int> tour, double distance) ConstructTour()
|
|
|
+ private (List<int> tour, double distance)? ConstructTour()
|
|
|
{
|
|
|
List<int> tour = [];
|
|
|
var visited = new bool[numberOfCities];
|
|
@@ -110,12 +110,14 @@ public class AntColonyOptimizer
|
|
|
// Строим путь
|
|
|
while (tour.Count < numberOfCities)
|
|
|
{
|
|
|
- int nextCity = SelectNextCity(currentCity, visited);
|
|
|
+ var sel = SelectNextCity(currentCity, visited);
|
|
|
+ if (sel is not { } nextCity) return null;
|
|
|
tour.Add(nextCity);
|
|
|
visited[nextCity] = true;
|
|
|
currentCity = nextCity;
|
|
|
}
|
|
|
|
|
|
+ if (distances[currentCity][tour[0]] == 0) return null;
|
|
|
// Добавляем возврат на начальную точку
|
|
|
tour.Add(tour[0]);
|
|
|
|
|
@@ -128,7 +130,7 @@ public class AntColonyOptimizer
|
|
|
/// <param name="currentCity">В каком городе муравей находится сейчас</param>
|
|
|
/// <param name="visited">Какие города муравей уже посетил</param>
|
|
|
/// <returns>Номер следующего города</returns>
|
|
|
- private int SelectNextCity(int currentCity, bool[] visited)
|
|
|
+ private int? SelectNextCity(int currentCity, bool[] visited)
|
|
|
{
|
|
|
var probabilities = new double[numberOfCities];
|
|
|
double probabilitiesSum = 0;
|
|
@@ -147,20 +149,19 @@ public class AntColonyOptimizer
|
|
|
|
|
|
// Случайно выбираем следующий город (по вероятностям)
|
|
|
double randomValue = Random.Shared.NextDouble() * probabilitiesSum;
|
|
|
- double sum = 0;
|
|
|
+ //double sum = 0;
|
|
|
|
|
|
for (int i = 0; i < numberOfCities; i++)
|
|
|
{
|
|
|
if (!visited[i])
|
|
|
{
|
|
|
- sum += probabilities[i];
|
|
|
- if (sum >= randomValue)
|
|
|
+ //sum += probabilities[i];
|
|
|
+ if (probabilities[i] >= randomValue)
|
|
|
return i;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- // Иначе возвращаемся к первому непосещенному городу
|
|
|
- return Array.FindIndex(visited, v => !v);
|
|
|
+ return null;
|
|
|
}
|
|
|
|
|
|
/// <summary>
|