예제 #1
0
        public static int GetMaxCost(Knapsack knapsack)
        {
            var items = knapsack.Items.Where(item => item.Weight <= knapsack.Capacity).ToArray();
            var optimalSolution = new int[items.Length, knapsack.Capacity + 1];

            for (int w = items[0].Weight; w <= knapsack.Capacity; w++)
            {
                optimalSolution[0, w] = items[0].Cost;
            }

            for (int i = 1; i < items.Length; i++)
            {
                var item = items[i];
                for (int w = 1; w <= knapsack.Capacity; w++)
                    if (w < item.Weight)
                    {
                        optimalSolution[i, w] = optimalSolution[i - 1, w];
                    }
                    else
                    {
                        optimalSolution[i, w] = Math.Max(optimalSolution[i - 1, w], optimalSolution[i - 1, w - item.Weight] + item.Cost);
                    }
            }

            return optimalSolution[items.Length - 1, knapsack.Capacity];
        }
예제 #2
0
 public void GetBigKnapsackMaxCostTest()
 {
     var items = new[] { new KnapsackItem(3, 4), new KnapsackItem(2, 3), new KnapsackItem(4, 2), new KnapsackItem(4, 3) };
     var knapsack = new Knapsack(items, 6);
     var solver = new BigKnapsackSolver(knapsack);
     solver.GetMaxCost().Should().Be(8);
 }
예제 #3
0
 public BigKnapsackSolver(Knapsack knapsack)
 {
     _items = new ReadOnlyCollection<KnapsackItem>(knapsack.Items.Where(item => item.Weight <= knapsack.Capacity).ToArray());
     _capacity = knapsack.Capacity;
     _calculatedMaxCosts = new Dictionary<int, int>[_items.Count];
     for (int i = 0; i < _items.Count; i++)
     {
         _calculatedMaxCosts[i] = new Dictionary<int, int>();
     }
 }