Exemplo n.º 1
0
        public override KnapsackSolution Solve()
        {
            Items = Items.OrderByDescending(i => i.Ratio).ToList();
            var node = new Node();

            foreach (var item in Items)
            {
                if (node.Weight <= Capacity)
                {
                    if (Capacity - node.Weight >= item.Weight)
                    {
                        node.TakenItems.Add(item);
                        node.Weight += item.Weight;
                        node.Value  += item.Value;
                    }
                }
            }
            var solution = new KnapsackSolution
            {
                Value       = node.Value,
                TotalWeight = node.Weight,
                Items       = node.TakenItems,
                Approach    = "Greedy Algorithm"
            };

            return(solution);
        }
Exemplo n.º 2
0
        public void Pick(KnapsackCase testcase)
        {
            var expect   = testcase.Best;
            var solution = new KnapsackSolution();
            var best     = solution.Pick(testcase.Capacity, testcase.Items);

            Assert.AreEqual(expect, best.Value);
        }
Exemplo n.º 3
0
        // For brute force we evaluate every possible combination of N Items (in ALL K Slots)

        // Possible Solutions = 2^N  (when including all possible values for K)
        // 1234 == 00,1,2,3,4,12,13,14,23,24,34,123,124,134,234
        // 24 / (24 *
        // N! / (K! * (N -K)!)

        // 123 == 321 == 132 == 321 ETC (order does not matter)
        // 1234 (N=4, K=2) 12,13,14,23,24,34,
        // 4! / (2! * (4-2)!) == 24 / ( 2 * 2) == 24/4 == 6

        private void HandleSolution(KSItem[] solution)
        {
            SolutionCount++;
            KnapsackSolution curSolution = new KnapsackSolution(TM);

            for (int s = 0; s < solution.Length; s++)
            {
                curSolution.TryAddItem(solution[s]);
            }

            if (OptimalSolution == null || curSolution.Result.Value > OptimalSolution.Result.Value)
            {
                OptimalSolution = curSolution;
            }
        }
Exemplo n.º 4
0
        private void HandleSolution(KSItem[] items)
        {
            SolutionCount++;
            KnapsackSolution curSolution = new KnapsackSolution(TM);

            //in the permutation scenario the order the items are added to the knapsack are important (the constraints maybe violated)
            for (int s = 0; s < items.Length; s++)
            {
                curSolution.TryAddItem(items[s]);
            }

            if (OptimalSolution == null || curSolution.Result.Value > OptimalSolution.Result.Value)
            {
                OptimalSolution = curSolution;
            }

            return;
        }
Exemplo n.º 5
0
        public static void KnapsackTest()
        {
            Console.WriteLine("============");
            Console.WriteLine("SA Knapsack problem example");
            Console.WriteLine("Knapsack instances are generated according to this paper:");
            Console.WriteLine("http://www.dcs.gla.ac.uk/~pat/cpM/jchoco/knapsack/papers/hardInstances.pdf");
            Console.WriteLine("============");
            var logger = new Logger <SimulatedAnnealing <KnapsackSolution> >(new LoggerFactory());
            var cooler = new QuadraticCooler(0.998, 800);
            var mover  = new KnapsackMover();

            var instances = new KnapsackInstancesFactory(50, 5000, 1)
                            .GenDistribution(DistributionVariant.Strong, 3)
                            .GenDistribution(DistributionVariant.Uncorrelated, 3)
                            .Collect();

            var stop = new NotGettingBetter <KnapsackSolution>(cooler, OptimizationType.Maximization, 500000, 300000);

            Console.WriteLine("COMMON ELEMENTS");
            Console.WriteLine($"    Stop criteria: {stop}");
            Console.WriteLine($"    Cooler: {cooler}");
            Console.WriteLine("INSTANCES");
            for (int i = 0; i < instances.Count; i++)
            {
                var instance = instances[i];
                Console.WriteLine($"Instance name: {instance.Name}");

                var sa         = new SimulatedAnnealing <KnapsackSolution>(cooler, mover, stop, logger);
                var obj        = new KnapsackObj(instance);
                var constraint = new KnapsackConstraint(instance);

                var objAggr        = new WeightedObjectiveAggregator <KnapsackSolution>(new[] { obj }, new double[] { 1 });
                var constraintAggr = new WeightedConstraintAggregator <KnapsackSolution>(new[] { constraint }, new double[] { 1 });
                var criterion      = new Criterion <KnapsackSolution>(OptimizationType.Maximization, objAggr, constraintAggr);

                var solution = new KnapsackSolution(instance);

                var bestSol = sa.Solve(solution, criterion);

                Console.WriteLine(instance);
                Console.WriteLine(bestSol);
                Console.WriteLine("----");
            }
        }
Exemplo n.º 6
0
        private KnapsackSolution TakeItems()
        {
            var best = new KnapsackSolution()
            {
                Items = new List <Item>()
            };

            for (int row = this.Items.Count, col = this.Capacity; row > 0; row--)
            {
                if (this.table[row, col] != this.table[row - 1, col])
                {
                    best.Items.Add(this.Items[row - 1]);
                    col -= this.Items[row - 1].Weight;
                }
            }

            best.TotalWeight = this.GetWeight(best.Items);
            best.Value       = this.GetValue(best.Items);
            return(best);
        }
Exemplo n.º 7
0
        public override KnapsackSolution Solve()
        {
            this.Items = this.Items.OrderByDescending(i => i.Ratio).ToList();

            Node best = new Node();
            Node root = new Node();

            root.ComputeBound(this.Items, this.Capacity);

            var queue = new PriorityQueue <Node>();

            queue.Enqueue(root);

            while (queue.Count != 0)
            {
                var node = queue.Dequeue();

                if (node.Bound > best.Value && node.Height < this.Items.Count - 1)
                {
                    Node with = new Node(node);

                    var item = this.Items[node.Height];
                    with.Weight += item.Weight;

                    if (with.Weight <= this.Capacity)
                    {
                        with.TakenItems.Add(this.Items[node.Height]);
                        with.Value += item.Value;
                        with.ComputeBound(this.Items, this.Capacity);

                        if (with.Value > best.Value)
                        {
                            best = with;
                        }

                        if (with.Bound > best.Value)
                        {
                            queue.Enqueue(with);
                        }
                    }

                    var without = new Node(node);
                    without.ComputeBound(this.Items, this.Capacity);

                    if (without.Bound > best.Value)
                    {
                        queue.Enqueue(without);
                    }
                }
            }

            var solution = new KnapsackSolution
            {
                Value       = best.Value,
                TotalWeight = best.Weight,
                Items       = best.TakenItems,
                Approach    = "Best-First Search with Branch and Bound"
            };

            return(solution);
        }
Exemplo n.º 8
0
        public override KnapsackSolution Solve()
        {
            KnapsackSolver knapsackSol = new DynamicProgrammingSolver(Items, Capacity);
            var            sol         = knapsackSol.Solve();

            Items = Items.OrderByDescending(i => i.Ratio).ToList();
            List <Item> editItems = new List <Item>(Items);
            var         myArray   = editItems.ToArray();
            var         node      = new Node();
            var         tempNode  = new Node();
            int         minWeight = int.MaxValue;
            Random      random    = new Random();

            foreach (var item in editItems)
            {
                if (item.Weight < minWeight)
                {
                    minWeight = item.Weight;
                }
            }
            while (node.Value != sol.Value)
            {
                editItems.Clear();
                editItems = new List <Item>(Items);
                while (Capacity - tempNode.Weight >= minWeight)
                {
                    if (editItems.Count() == 0)
                    {
                        break;
                    }
                    myArray = editItems.ToArray();
                    int index = random.Next(myArray.Length);
                    var item  = myArray[index];
                    minWeight = int.MaxValue;
                    foreach (var i in editItems)
                    {
                        if (i.Weight < minWeight)
                        {
                            minWeight = i.Weight;
                        }
                    }

                    if (Capacity - tempNode.Weight >= item.Weight && !tempNode.TakenItems.Contains(item))
                    {
                        tempNode.TakenItems.Add(item);
                        tempNode.Weight += item.Weight;
                        tempNode.Value  += item.Value;
                        editItems.RemoveAt(index);
                    }
                }
                node     = tempNode;
                tempNode = new Node();
            }
            var solution = new KnapsackSolution
            {
                Value       = node.Value,
                TotalWeight = node.Weight,
                Items       = node.TakenItems,
                Capacity    = Capacity,
                Approach    = "Bad random Algorithm"
            };

            return(solution);
        }