| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System.Collections.Generic;
- using System.Linq;
- namespace MetaheuristicsPCL
- {
- public class ParticleSwarmOptimizationForKnapsack : ParticleSwarmOptimizationAlgorithm
- {
- int nbIterations = 1;
- private const int MAX_ITERATIONS = 200;
- protected override void UpdateSolutions()
- {
- List<Box> possibleBoxes = ((KnapsackProblem)pb).Boxes();
- foreach (ISolution genericSolution in currentSolutions)
- {
- KnapsackSolution solution = (KnapsackSolution)genericSolution;
- if (!solution.Equals(bestSoFarSolution))
- {
- int index = KnapsackProblem.randomGenerator.Next(0, ((KnapsackSolution)bestActualSolution).LoadedContent.Count);
- Box element = ((KnapsackSolution)bestActualSolution).LoadedContent.ElementAt(index);
- if (!solution.LoadedContent.Contains(element))
- {
- solution.LoadedContent.Add(element);
- }
- index = KnapsackProblem.randomGenerator.Next(0, ((KnapsackSolution)bestSoFarSolution).LoadedContent.Count);
- element = ((KnapsackSolution)bestSoFarSolution).LoadedContent.ElementAt(index);
- if (!solution.LoadedContent.Contains(element))
- {
- solution.LoadedContent.Add(element);
- }
- while (solution.Weight > ((KnapsackProblem)pb).MaxWeight)
- {
- index = KnapsackProblem.randomGenerator.Next(0, solution.LoadedContent.Count);
- solution.LoadedContent.RemoveAt(index);
- }
- double enableSpace = ((KnapsackProblem)pb).MaxWeight - solution.Weight;
- List<Box> availableBoxes = possibleBoxes.Except(solution.LoadedContent).Where(x => (x.Weight <= enableSpace)).ToList();
- while (enableSpace > 0 && availableBoxes.Count != 0)
- {
- index = KnapsackProblem.randomGenerator.Next(0, availableBoxes.Count);
- solution.LoadedContent.Add(availableBoxes.ElementAt(index));
- enableSpace = ((KnapsackProblem)pb).MaxWeight - solution.Weight;
- availableBoxes = possibleBoxes.Except(solution.LoadedContent).Where(x => (x.Weight <= enableSpace)).ToList();
- }
- }
- }
- }
- protected override void UpdateGeneralVariables()
- {
- bestActualSolution = currentSolutions.OrderByDescending(x => x.Value).FirstOrDefault();
- if (bestActualSolution.Value > bestSoFarSolution.Value)
- {
- bestSoFarSolution = bestActualSolution;
- }
- }
- protected override bool Done()
- {
- return nbIterations >= MAX_ITERATIONS;
- }
- protected override void Increment()
- {
- nbIterations++;
- }
- protected override void SendResult()
- {
- ihm.PrintMessage(bestSoFarSolution.ToString());
- }
- }
- }
|