Skip to main content

fractional_knapsack

Function fractional_knapsack 

Source
pub fn fractional_knapsack(
    values: &[f64],
    weights: &[f64],
    capacity: f64,
) -> OptimizeResult<f64>
Expand description

Solve the fractional knapsack problem with a greedy algorithm.

Items can be taken as fractions; the optimal solution is obtained by sorting items by value-to-weight ratio and filling greedily.

Returns the maximum total value achievable.

§Arguments

  • values – item values (non-negative)
  • weights – item weights (non-negative, items with weight 0 are taken first)
  • capacity – total capacity

§Errors

Returns OptimizeError::InvalidInput on length mismatch or negative inputs.

§Example

use scirs2_optimize::integer::knapsack::fractional_knapsack;

let values  = vec![60.0, 100.0, 120.0];
let weights = vec![10.0,  20.0,  30.0];
let val = fractional_knapsack(&values, &weights, 50.0).expect("valid input");
assert!((val - 240.0).abs() < 1e-6);