TabuSearchForKnapsack.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace MetaheuristicsPCL
  4. {
  5. public class TabuSearchForKnapsack : TabuSearchAlgorithm
  6. {
  7. int nbIterationsWithoutUpdate = 1;
  8. int nbIterations = 1;
  9. private const int MAX_ITERATIONS_WITHOUT_UPDATE = 30;
  10. private const int MAX_ITERATIONS = 100;
  11. private const int TABU_SEARCH_MAX_SIZE = 50;
  12. List<KnapsackSolution> tabuSolutions = new List<KnapsackSolution>();
  13. protected override bool Done()
  14. {
  15. return nbIterationsWithoutUpdate >= MAX_ITERATIONS_WITHOUT_UPDATE && nbIterations >= MAX_ITERATIONS;
  16. }
  17. protected override void UpdateSolution(ISolution _bestSolution)
  18. {
  19. if (!tabuSolutions.Contains((KnapsackSolution)_bestSolution))
  20. {
  21. currentSolution = _bestSolution;
  22. AddToTabuList((KnapsackSolution)_bestSolution);
  23. if (_bestSolution.Value > bestSoFarSolution.Value)
  24. {
  25. bestSoFarSolution = _bestSolution;
  26. nbIterationsWithoutUpdate = 0;
  27. }
  28. }
  29. }
  30. protected override void Increment()
  31. {
  32. nbIterationsWithoutUpdate++;
  33. nbIterations++;
  34. }
  35. protected override void SendResult()
  36. {
  37. ihm.PrintMessage(bestSoFarSolution.ToString());
  38. }
  39. protected override void AddToTabuList(ISolution _solution)
  40. {
  41. while (tabuSolutions.Count >= TABU_SEARCH_MAX_SIZE)
  42. {
  43. tabuSolutions.RemoveAt(0);
  44. }
  45. tabuSolutions.Add((KnapsackSolution)_solution);
  46. }
  47. protected override List<ISolution> RemoveSolutionsInTabuList(List<ISolution> Neighbours)
  48. {
  49. return Neighbours.Except(tabuSolutions).ToList();
  50. }
  51. }
  52. }