Skip to main content

knapsack_dp

Function knapsack_dp 

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

Solve the 0-1 knapsack problem with dynamic programming.

Maximizes sum(values[i] * x[i]) subject to sum(weights[i] * x[i]) <= capacity and x[i] in {0, 1}.

Weights are converted to integer indices by multiplying by a scaling factor so that the DP table has size n * (scaled_capacity + 1).

§Arguments

  • values – item values (must be non-negative)
  • weights – item weights (must be non-negative)
  • capacity – knapsack capacity (must be non-negative)

§Returns

(optimal_value, selection) where selection[i] is true iff item i is included.

§Errors

Returns OptimizeError::InvalidInput if the inputs have different lengths or if any value/weight is negative.

§Example

use scirs2_optimize::integer::knapsack::knapsack_dp;

let values  = vec![4.0, 3.0, 5.0, 2.0, 6.0];
let weights = vec![2.0, 3.0, 4.0, 1.0, 5.0];
let (val, sel) = knapsack_dp(&values, &weights, 8.0).expect("valid input");
assert!((val - 12.0).abs() < 1e-6);
assert_eq!(sel, vec![true, false, false, true, true]);