Beispiel #1
0
        public static int NaiveCalculation(KnapsackInfo info, List <KnapsackData> data)
        {
            int[,] memo = new int[info.Items + 1, info.TotalWeight + 1];

            for (int i = 1; i <= info.Items; i++)
            {
                KnapsackData item = data[i - 1];
                for (int w = 1; w <= info.TotalWeight; w++)
                {
                    var sackSkippingItem = memo[i - 1, w];
                    if (item.Weight > w)
                    {
                        memo[i, w] = sackSkippingItem;
                    }
                    else
                    {
                        var sackIncludingItem = memo[i - 1, w - item.Weight] + item.Value;
                        memo[i, w] = Math.Max(sackSkippingItem, sackIncludingItem);
                    }
                }
            }

            return(memo[info.Items, info.TotalWeight]);
        }
Beispiel #2
0
 public static int SmarterCalculation(KnapsackInfo info, List <KnapsackData> data)
 {
     var memo = new (int cache, int result)[info.TotalWeight + 1];