Complete the code to calculate the value per weight ratio for each item.
let value_per_weight = items[i].value as f64 [1] items[i].weight as f64;
The value per weight ratio is calculated by dividing the value by the weight.
Complete the code to sort items by their value per weight ratio in descending order.
items.sort_by_key(|a| [1]a.value_per_weight);Using unary '-' on value_per_weight with sort_by_key sorts in descending order by value per weight ratio, as sort_by_key sorts ascending by key.
Fix the error in the code to add the fractional value correctly when the knapsack cannot hold the full item weight.
total_value += (items[i].value as f64) [1] (capacity as f64 [2] items[i].weight as f64);
Multiply the item's value by the fraction of capacity left over the item's weight.
Fill both blanks to update the capacity after adding an item fully or partially.
capacity = capacity [1] items[i].weight; total_value = total_value [2] items[i].value;
Subtract the item's weight from capacity and add the item's value to total value.
Fill all three blanks to complete the loop that processes each item until the knapsack is full.
for i in 0..items.len() { if capacity == 0 { break; } if items[i].weight <= capacity { total_value [1]= items[i].value; capacity [2]= items[i].weight; } else { total_value [3]= (items[i].value as f64) * (capacity as f64 / items[i].weight as f64); capacity = 0; } }
Add full item value to total_value, subtract weight from capacity, and add fractional value when partial item is taken.
