Complete the code to calculate the value-to-weight ratio for each item.
double ratio = items[i].value [1] items[i].weight;The value-to-weight ratio is calculated by dividing the value by the weight.
Complete the code to sort items by their value-to-weight ratio in descending order.
Array.Sort(items, (a, b) => b.[1].CompareTo(a.[1]));
We sort items by their ratio to pick the best value per weight first.
Fix the error in the loop condition to stop when knapsack is full or all items are processed.
for (int i = 0; i [1] items.Length && capacity > 0; i++)
The loop should continue while i is less than the number of items.
Fill both blanks to add the full item value or fractional value to totalValue and reduce capacity.
if (items[i].weight <= capacity) { totalValue += items[i].value; capacity [1]= items[i].weight; } else { double fraction = (double)capacity [2] items[i].weight; totalValue += items[i].value * fraction; capacity = 0; }
We subtract the item's weight from capacity and calculate fraction by dividing capacity by item's weight.
Fill all three blanks to create a dictionary of item indices and their fractional amounts taken.
Dictionary<int, double> fractions = new Dictionary<int, double>(); for (int i = 0; i < items.Length; i++) { double fraction = (capacity > 0) ? Math.Min(1, (double)capacity [1] items[i].weight) : 0; fractions[items[i].[2]] = fraction; capacity [3]= (int)(items[i].weight * fraction); }
Fraction is capacity divided by weight, key is item index, capacity reduces by weight times fraction.
