ParticleSwarmOptimizationForKnapsack.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace MetaheuristicsPCL
  4. {
  5. public class ParticleSwarmOptimizationForKnapsack : ParticleSwarmOptimizationAlgorithm
  6. {
  7. int nbIterations = 1;
  8. private const int MAX_ITERATIONS = 200;
  9. protected override void UpdateSolutions()
  10. {
  11. List<Box> possibleBoxes = ((KnapsackProblem)pb).Boxes();
  12. foreach (ISolution genericSolution in currentSolutions)
  13. {
  14. KnapsackSolution solution = (KnapsackSolution)genericSolution;
  15. if (!solution.Equals(bestSoFarSolution))
  16. {
  17. int index = KnapsackProblem.randomGenerator.Next(0, ((KnapsackSolution)bestActualSolution).LoadedContent.Count);
  18. Box element = ((KnapsackSolution)bestActualSolution).LoadedContent.ElementAt(index);
  19. if (!solution.LoadedContent.Contains(element))
  20. {
  21. solution.LoadedContent.Add(element);
  22. }
  23. index = KnapsackProblem.randomGenerator.Next(0, ((KnapsackSolution)bestSoFarSolution).LoadedContent.Count);
  24. element = ((KnapsackSolution)bestSoFarSolution).LoadedContent.ElementAt(index);
  25. if (!solution.LoadedContent.Contains(element))
  26. {
  27. solution.LoadedContent.Add(element);
  28. }
  29. while (solution.Weight > ((KnapsackProblem)pb).MaxWeight)
  30. {
  31. index = KnapsackProblem.randomGenerator.Next(0, solution.LoadedContent.Count);
  32. solution.LoadedContent.RemoveAt(index);
  33. }
  34. double enableSpace = ((KnapsackProblem)pb).MaxWeight - solution.Weight;
  35. List<Box> availableBoxes = possibleBoxes.Except(solution.LoadedContent).Where(x => (x.Weight <= enableSpace)).ToList();
  36. while (enableSpace > 0 && availableBoxes.Count != 0)
  37. {
  38. index = KnapsackProblem.randomGenerator.Next(0, availableBoxes.Count);
  39. solution.LoadedContent.Add(availableBoxes.ElementAt(index));
  40. enableSpace = ((KnapsackProblem)pb).MaxWeight - solution.Weight;
  41. availableBoxes = possibleBoxes.Except(solution.LoadedContent).Where(x => (x.Weight <= enableSpace)).ToList();
  42. }
  43. }
  44. }
  45. }
  46. protected override void UpdateGeneralVariables()
  47. {
  48. bestActualSolution = currentSolutions.OrderByDescending(x => x.Value).FirstOrDefault();
  49. if (bestActualSolution.Value > bestSoFarSolution.Value)
  50. {
  51. bestSoFarSolution = bestActualSolution;
  52. }
  53. }
  54. protected override bool Done()
  55. {
  56. return nbIterations >= MAX_ITERATIONS;
  57. }
  58. protected override void Increment()
  59. {
  60. nbIterations++;
  61. }
  62. protected override void SendResult()
  63. {
  64. ihm.PrintMessage(bestSoFarSolution.ToString());
  65. }
  66. }
  67. }