//Dynamic programming algorithm private static Knapsack FillKnapsack(int maxWeight, List <Item> items) { Knapsack[] sacks = new Knapsack[maxWeight + 1]; sacks[0] = new Knapsack(0); Knapsack bestSack; for (int w = 1; w <= maxWeight; w++) { bestSack = sacks[w - 1]; sacks[w] = new Knapsack(w); for (int i = 0; i < items.Count; i++) { int currVal = items[i].value; int currWeight = items[i].weight; if (currWeight < w) { if ((sacks[w - currWeight].value + currVal) > bestSack.value) { bestSack = new Knapsack(w); foreach (Item item in sacks[w - currWeight]) { bestSack.Add(item); } bestSack.Add(items[i]); } } else if (currWeight == w) { if (currVal > bestSack.value) { bestSack = new Knapsack(w); bestSack.Add(items[i]); } } } sacks[w] = bestSack; } return(sacks[maxWeight]); }
public static void KnapsackProblem() { Console.WriteLine("Task#6 (items are infinite)"); List <Item> items = new List <Item>(); if (GetInput(items)) { //Getting max weight capacity Console.WriteLine("Input an integer knapsack max weight capacity:"); var consoleInput = Console.ReadLine(); //Trying to parse the input int capacity = 0; if (!int.TryParse(consoleInput, out capacity) || capacity <= 0) { Console.WriteLine($"\"{consoleInput}\" is too big, too small or is not an integer"); return; } Knapsack sack = FillKnapsack(capacity, items); //Writing contained items, sum of values and weights to console Console.WriteLine("Knapsack contains:"); int sackWeight = 0; foreach (Item item in sack) { Console.Write($"(v:{item.value}, w:{item.weight}) "); sackWeight += item.weight; } Console.WriteLine($"\nSum: (v:{sack.value}, w:{sackWeight}/{capacity})\n" + $"Knapsack value is: {sack.value}"); Console.WriteLine(); } else { return; } }