示例#1
0
        public void CapacityZeroTest()
        {
            List <int> solution;

            // 0 capacity, 0 items => 0
            solution = KnapsackProblem.Solve(0, new List <Item>());
            Assert.AreEqual(solution.Count, 0);


            // 0 capacity, 1 item => 0
            List <Item> items = new List <Item>
            {
                new Item(5, 5)
            };

            solution = KnapsackProblem.Solve(0, items);
            Assert.AreEqual(solution.Count, 0);


            // 0 capacity, bunch of items => 0
            items = new List <Item>();
            for (int i = 0; i < 100; i++)
            {
                items.Add(new Item(this._Rand.Next(), this._Rand.Next()));
            }

            solution = KnapsackProblem.Solve(0, items);
            Assert.AreEqual(solution.Count, 0);
        }
示例#2
0
 private async void calculateMatrixDynamic(object sender, RoutedEventArgs e)
 {
     try
     {
         Matrix   matrix      = getMatrixFromGrid(gridTextBox);
         int      capacity    = int.Parse(capacityTextBox.Text);
         Matrix[] pq          = KnapsackProblem.DynamicMethod(matrix, capacity);
         int[]    resultTable = KnapsackProblem.ShowItems(matrix, pq[1]);
         resultDynamicTextBlock.Text         = "Przedmioty do zabrania: " + string.Join(",", resultTable.Select(i => i.ToString()));
         resultDynamicSumTextBlock.Text      = "Wartość Plecaka: " + pq[0].getMatrix()[pq[0].getMatrix().GetLength(0) - 1, pq[0].getMatrix().GetLength(1) - 1].ToString();
         resultGridDynamic.Visibility        = Visibility.Visible;
         resultGridDynamic.Opacity           = 0;
         resultGridDynamic.OpacityTransition = new ScalarTransition()
         {
             Duration = new TimeSpan(0, 0, 0, 0, 500)
         };
         resultGridDynamic.Opacity = 1;
     }
     catch (Exception exp)
     {
         ContentDialog dialog = new ContentDialog {
             Title = "Error", Content = exp.Message, CloseButtonText = "ok"
         };
         ContentDialogResult result = await dialog.ShowAsync();
     }
 }
示例#3
0
        public void CombineLessValuableTest()
        {
            List <int> solution;

            // Most valuable item should be the only one included
            List <Item> items = new List <Item>
            {
                new Item(55, 55),
                new Item(50, 45),
                new Item(50, 45)
            };

            solution = KnapsackProblem.Solve(100, items);
            Assert.AreEqual(solution.Count, 2);
            Assert.IsTrue(solution.Contains(1));
            Assert.IsTrue(solution.Contains(2));
        }
        public void ResolveTest()
        {
            var maxWeight = 6;
            var result    = KnapsackProblem.Resolve(CreateThings(), maxWeight);
            var sumWeight = result.Sum(thing => thing.Weight);
            var sumValue  = result.Sum(thing => thing.Value);

            Assert.IsTrue(sumWeight <= maxWeight);

            Console.WriteLine($"SumValue:{sumValue}, SumWeight:{sumWeight}, MaxWeight:{maxWeight}");
            Console.WriteLine("Result[] = {");
            foreach (var thing in result)
            {
                Console.WriteLine($"    Value:{thing.Value}, Weight:{thing.Weight}");
            }
            Console.WriteLine("}");
        }
        private LocalSearch CreateLocalSearchKnapsackSample()
        {
            LocalSearch ls = new LocalSearch();

            #region Problem Configuration
            KnapsackProblem problem = new KnapsackProblem();
            problem.BestKnownQuality  = new DoubleValue(362);
            problem.BestKnownSolution = new HeuristicLab.Encodings.BinaryVectorEncoding.BinaryVector(new bool[] {
                true, false, false, true, true, true, true, true, false, true, true, true, true, true, true, false, true, false, true, true, false, true, true, false, true, false, true, true, true, false, true, true, false, true, true, false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, false, true, true, false, true, true, true, true, true, true, true, true, false, true, false, true, true, true, true, false, true, true, true, true, true, true, true, true
            });
            problem.EvaluatorParameter.Value       = new KnapsackEvaluator();
            problem.SolutionCreatorParameter.Value = new RandomBinaryVectorCreator();
            problem.KnapsackCapacity.Value         = 297;
            problem.Maximization.Value             = true;
            problem.Penalty.Value = 1;
            problem.Values        = new IntArray(new int[] {
                6, 1, 1, 6, 7, 8, 7, 4, 2, 5, 2, 6, 7, 8, 7, 1, 7, 1, 9, 4, 2, 6, 5, 3, 5, 3, 3, 6, 5, 2, 4, 9, 4, 5, 7, 1, 4, 3, 5, 5, 8, 3, 6, 7, 3, 9, 7, 7, 5, 5, 7, 1, 4, 4, 3, 9, 5, 1, 6, 2, 2, 6, 1, 6, 5, 4, 4, 7, 1, 8, 9, 9, 7, 4, 3, 8, 7, 5, 7, 4, 4, 5
            });
            problem.Weights = new IntArray(new int[] {
                1, 9, 3, 6, 5, 3, 8, 1, 7, 4, 2, 1, 2, 7, 9, 9, 8, 4, 9, 2, 4, 8, 3, 7, 5, 7, 5, 5, 1, 9, 8, 7, 8, 9, 1, 3, 3, 8, 8, 5, 1, 2, 4, 3, 6, 9, 4, 4, 9, 7, 4, 5, 1, 9, 7, 6, 7, 4, 7, 1, 2, 1, 2, 9, 8, 6, 8, 4, 7, 6, 7, 5, 3, 9, 4, 7, 4, 6, 1, 2, 5, 4
            });
            problem.Name        = "Knapsack Problem";
            problem.Description = "Represents a Knapsack problem.";
            #endregion
            #region Algorithm Configuration
            ls.Name                    = "Local Search - Knapsack";
            ls.Description             = "A local search algorithm that solves a randomly generated Knapsack problem";
            ls.Problem                 = problem;
            ls.MaximumIterations.Value = 1000;
            ls.MoveEvaluator           = ls.MoveEvaluatorParameter.ValidValues
                                         .OfType <KnapsackOneBitflipMoveEvaluator>()
                                         .Single();
            ls.MoveGenerator = ls.MoveGeneratorParameter.ValidValues
                               .OfType <ExhaustiveOneBitflipMoveGenerator>()
                               .Single();
            ls.MoveMaker = ls.MoveMakerParameter.ValidValues
                           .OfType <OneBitflipMoveMaker>()
                           .Single();
            ls.SampleSize.Value      = 100;
            ls.Seed.Value            = 0;
            ls.SetSeedRandomly.Value = true;
            #endregion
            ls.Engine = new ParallelEngine.ParallelEngine();
            return(ls);
        }
示例#6
0
 private async void calculateMatrixGreedy(object sender, RoutedEventArgs e)
 {
     try
     {
         Matrix matrix   = getMatrixFromGrid(gridTextBox);
         int    capacity = int.Parse(capacityTextBox.Text);
         if (KnapsackProblem.CheckWeights(matrix, capacity) == 0)
         {
             ContentDialog dialog = new ContentDialog {
                 Title = "Information", Content = "Nic się nie zmieści do plecaka", CloseButtonText = "Ok"
             };
             ContentDialogResult result = await dialog.ShowAsync();
         }
         else
         {
             double[] quot      = KnapsackProblem.CountQuotient(matrix);
             int      value     = 0;
             Matrix   newMatrix = KnapsackProblem.GreedyMethod(matrix, capacity, quot, ref value);
             resultGreedySumTextBlock.Text = "Wartość Plecaka: " + value.ToString();
             resultGreedyTextBlock.Text    = "Przedmioty do zabrania: ";
             for (int i = 0; i < newMatrix.getMatrix().GetLength(1); i++)
             {
                 resultGreedyTextBlock.Text += " Przedmiot ";
                 resultGreedyTextBlock.Text += newMatrix.getMatrix()[1, i].ToString();
                 resultGreedyTextBlock.Text += " x ";
                 resultGreedyTextBlock.Text += newMatrix.getMatrix()[0, i].ToString();
                 resultGreedyTextBlock.Text += " ; ";
             }
             resultGridGreedy.Visibility        = Visibility.Visible;
             resultGridGreedy.Opacity           = 0;
             resultGridGreedy.OpacityTransition = new ScalarTransition()
             {
                 Duration = new TimeSpan(0, 0, 0, 0, 500)
             };
             resultGridGreedy.Opacity = 1;
         }
     }
     catch (Exception exp)
     {
         ContentDialog dialog = new ContentDialog {
             Title = "Error", Content = exp.Message, CloseButtonText = "ok"
         };
         ContentDialogResult result = await dialog.ShowAsync();
     }
 }
示例#7
0
        public void SearchTest()
        {
            var capacity = 14;
            var items    = new KnapsackItem[]
            {
                new KnapsackItem(weight: 1, value: 13),
                new KnapsackItem(weight: 6, value: 5),
                new KnapsackItem(weight: 6, value: 4),
                new KnapsackItem(weight: 5, value: 2)
            };

            var result    = KnapsackProblem.Search(items, capacity);
            var backTrack = KnapsackProblem.GetBackTrack(result, items, capacity, items.Length);

            const int expectedSumValue = 22;

            Assert.IsTrue(backTrack.Sum(i => i.Value) == expectedSumValue, "Incorrectly found the sum of the values");
        }
示例#8
0
        public void FindsSolutionTest()
        {
            for (int i = 0; i < 10; i++)
            {
                List <Item> items = new List <Item>();

                for (int j = 0; j < 1000; j++)
                {
                    Item item = new Item(this._Rand.Next(1, 1000), this._Rand.Next());
                    items.Add(item);
                }

                List <int> weights           = items.Select(item => item.Weight).ToList();
                int        capacity          = this._Rand.Next(weights.Min(), weights.Max());
                List <int> solution          = KnapsackProblem.Solve(capacity, items);
                int        totalUsedCapacity = solution.Sum(s => weights[s]);
                Assert.IsTrue(totalUsedCapacity <= capacity);
            }
        }
示例#9
0
        protected void Run()
        {
            Console.Out.WriteLine("Métaheuristiques d'optimisation\n");

            IProblem kspb = new KnapsackProblem();

            RunAlgorithms(kspb);

            Console.Out.WriteLine("*****************************************************************\n");

            IProblem kspbRandom = new KnapsackProblem(100, 30, 20);

            RunAlgorithms(kspbRandom);

            Console.Out.WriteLine("FIN");
            while (true)
            {
                ;
            }
        }
    private LocalSearch CreateLocalSearchKnapsackSample() {
      LocalSearch ls = new LocalSearch();
      #region Problem Configuration
      KnapsackProblem problem = new KnapsackProblem();
      problem.BestKnownQuality = new DoubleValue(362);
      problem.BestKnownSolution = new HeuristicLab.Encodings.BinaryVectorEncoding.BinaryVector(new bool[] { 
       true , false, false, true , true , true , true , true , false, true , true , true , true , true , true , false, true , false, true , true , false, true , true , false, true , false, true , true , true , false, true , true , false, true , true , false, true , false, true , true , true , true , true , true , true , true , true , true , true , true , true , false, true , false, false, true , true , false, true , true , true , true , true , true , true , true , false, true , false, true , true , true , true , false, true , true , true , true , true , true , true , true});
      problem.EvaluatorParameter.Value = new KnapsackEvaluator();
      problem.SolutionCreatorParameter.Value = new RandomBinaryVectorCreator();
      problem.KnapsackCapacity.Value = 297;
      problem.Maximization.Value = true;
      problem.Penalty.Value = 1;
      problem.Values = new IntArray(new int[] { 
  6, 1, 1, 6, 7, 8, 7, 4, 2, 5, 2, 6, 7, 8, 7, 1, 7, 1, 9, 4, 2, 6, 5,  3, 5, 3, 3, 6, 5, 2, 4, 9, 4, 5, 7, 1, 4, 3, 5, 5, 8, 3, 6, 7, 3, 9, 7, 7, 5, 5, 7, 1, 4, 4, 3, 9, 5, 1, 6, 2, 2, 6, 1, 6, 5, 4, 4, 7, 1,  8, 9, 9, 7, 4, 3, 8, 7, 5, 7, 4, 4, 5});
      problem.Weights = new IntArray(new int[] { 
 1, 9, 3, 6, 5, 3, 8, 1, 7, 4, 2, 1, 2, 7, 9, 9, 8, 4, 9, 2, 4, 8, 3, 7, 5, 7, 5, 5, 1, 9, 8, 7, 8, 9, 1, 3, 3, 8, 8, 5, 1, 2, 4, 3, 6, 9, 4, 4, 9, 7, 4, 5, 1, 9, 7, 6, 7, 4, 7, 1, 2, 1, 2, 9, 8, 6, 8, 4, 7, 6, 7, 5, 3, 9, 4, 7, 4, 6, 1, 2, 5, 4});
      problem.Name = "Knapsack Problem";
      problem.Description = "Represents a Knapsack problem.";
      #endregion
      #region Algorithm Configuration
      ls.Name = "Local Search - Knapsack";
      ls.Description = "A local search algorithm that solves a randomly generated Knapsack problem";
      ls.Problem = problem;
      ls.MaximumIterations.Value = 1000;
      ls.MoveEvaluator = ls.MoveEvaluatorParameter.ValidValues
        .OfType<KnapsackOneBitflipMoveEvaluator>()
        .Single();
      ls.MoveGenerator = ls.MoveGeneratorParameter.ValidValues
        .OfType<ExhaustiveOneBitflipMoveGenerator>()
        .Single();
      ls.MoveMaker = ls.MoveMakerParameter.ValidValues
        .OfType<OneBitflipMoveMaker>()
        .Single();
      ls.SampleSize.Value = 100;
      ls.Seed.Value = 0;
      ls.SetSeedRandomly.Value = true;
      #endregion
      ls.Engine = new ParallelEngine.ParallelEngine();
      return ls;
    }
示例#11
0
        public void GreedyTest()
        {
            List <int> solution;

            // Most valuable item should be the only one included
            List <Item> items = new List <Item>
            {
                new Item(1, 500),
                new Item(1, 300),
                new Item(2, 500)
            };

            solution = KnapsackProblem.Solve(1, items);
            Assert.AreEqual(solution.Count, 1);
            Assert.IsTrue(solution.Contains(0));

            items.Add(new Item(1, 500));
            solution = KnapsackProblem.Solve(2, items);
            Assert.AreEqual(solution.Count, 2);
            Assert.IsTrue(solution.Contains(0));
            Assert.IsTrue(solution.Contains(3));
        }
 public KnapsackOptimizedSolver(KnapsackProblem problem)
 {
     _problem = problem;
 }
 public KnapsackIterativeSolver(KnapsackProblem problem)
 {
     _problem = problem;
 }