GreedyAlgorithmForKnapsack.cs 879 B

1234567891011121314151617181920212223242526272829303132
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace MetaheuristicsPCL
  4. {
  5. public class GreedyAlgorithmForKnapsack : GreedyAlgorithm
  6. {
  7. KnapsackSolution solution;
  8. protected override void ConstructSolution()
  9. {
  10. KnapsackProblem problem = (KnapsackProblem) pb;
  11. List<Box> boxes = problem.Boxes();
  12. solution = new KnapsackSolution();
  13. foreach(Box currentBox in boxes.OrderByDescending(x => x.Value / x.Weight))
  14. {
  15. double spaceLeft = problem.MaxWeight - solution.Weight;
  16. if (currentBox.Weight < spaceLeft)
  17. {
  18. solution.LoadedContent.Add(currentBox);
  19. }
  20. }
  21. }
  22. protected override void SendResult()
  23. {
  24. ihm.PrintMessage(solution.ToString());
  25. }
  26. }
  27. }