public override List <IIndividual> InitializePopulation() { var population = new List <IIndividual>(); var numCities = Problem.CityIds.Count; for (var i = 0; i < Parameters.PopulationSize; i++) { var randomRoadTaken = new List <int>(numCities); var mutableListCityIds = new List <int>(Problem.CityIds); for (var j = 0; j < numCities; j++) { var randomIndex = RandomNumGenerator.Next(0, mutableListCityIds.Count); var randomCityId = mutableListCityIds[randomIndex]; mutableListCityIds.RemoveAt(randomIndex); randomRoadTaken.Add(randomCityId); } var individual = new Ttp1Individual(randomRoadTaken); population.Add(individual); } return(population); }
private IIndividual Neighbour(IIndividual solution) { Ttp1Individual neighbour = null; neighbour = solution.DeepCopy() as Ttp1Individual; if (neighbour == null) { Console.WriteLine("Solution passed to Neighbour is not of type TabuTtp1Individual"); return(null); } var firstRandomSwapIndex = RandomNumGenerator.Next(0, neighbour.RoadTaken.Count); var secondRandomSwapIndex = RandomNumGenerator.Next(0, neighbour.RoadTaken.Count); while (firstRandomSwapIndex == secondRandomSwapIndex) { secondRandomSwapIndex = RandomNumGenerator.Next(0, neighbour.RoadTaken.Count); } var tmp = neighbour.RoadTaken[firstRandomSwapIndex]; neighbour.RoadTaken[firstRandomSwapIndex] = neighbour.RoadTaken[secondRandomSwapIndex]; neighbour.RoadTaken[secondRandomSwapIndex] = tmp; if (!neighbour.Equals(solution)) { return(neighbour); } Console.WriteLine("Neighbour equals solution."); return(null); }
public void Fitness() { var problemStats = new ProblemStats { NumCities = 4, NumItems = 5, KnapsackCapacity = 3, KnapsackRentingRatio = 1, MaxSpeed = 1, MinSpeed = 0.1 }; var cities = new List <int> { 1, 2, 3, 4 }; var interCityDistances = new Dictionary <CityCity, double> { { new CityCity(1, 2), 5 }, { new CityCity(1, 3), 6 }, { new CityCity(1, 4), 6 }, { new CityCity(2, 1), 5 }, { new CityCity(2, 3), 6 }, { new CityCity(2, 4), 6 }, { new CityCity(3, 1), 6 }, { new CityCity(3, 2), 5 }, { new CityCity(3, 4), 4 }, { new CityCity(4, 1), 6 }, { new CityCity(4, 2), 6 }, { new CityCity(4, 3), 4 } }; var items = new List <Item> { new Item { Id = 1, Profit = 100, Weight = 3, AssignedCityId = 3 }, new Item { Id = 2, Profit = 40, Weight = 1, AssignedCityId = 3 }, new Item { Id = 3, Profit = 40, Weight = 1, AssignedCityId = 3 }, new Item { Id = 4, Profit = 20, Weight = 2, AssignedCityId = 2 }, new Item { Id = 5, Profit = 20, Weight = 2, AssignedCityId = 4 }, new Item { Id = 6, Profit = 30, Weight = 3, AssignedCityId = 2 } }; var problemTtp1 = new ProblemTtp1(problemStats, cities, interCityDistances, items); var individual = new Ttp1Individual(new List <int> { 1, 3, 2, 4 }); var itemsTaken = new List <Item> { new Item { Id = 2, Profit = 40, Weight = 1, AssignedCityId = 3 }, new Item { Id = 4, Profit = 20, Weight = 2, AssignedCityId = 2 } }; Assert.Equal(-73.14, Math.Round(problemTtp1.Fitness(individual, itemsTaken), 2)); }