Skip to content

Commit cc6dda8

Browse files
authored
Merge pull request #206 from scipopt/knapsack-example
Improve readability
2 parents 83b8591 + a3dac45 commit cc6dda8

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

examples/knapsack.rs

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
use russcip::minimal_model;
22
use russcip::prelude::*;
33

4+
/// 0-1 Knapsack problem
45
#[derive(Debug)]
56
struct Knapsack {
7+
/// Sizes of the items
68
sizes: Vec<usize>,
9+
/// Values of the items
710
values: Vec<usize>,
11+
/// Capacity of the knapsack
812
capacity: usize,
913
}
1014

15+
/// Solution to the knapsack problem
1116
#[derive(Debug)]
1217
struct KnapsackSolution {
18+
/// Indices of the items in the solution
1319
items: Vec<usize>,
20+
/// Total value of the solution
1421
value: f64,
1522
}
1623

@@ -32,29 +39,27 @@ impl Knapsack {
3239
fn solve(&self) -> KnapsackSolution {
3340
let mut model = minimal_model().maximize();
3441

35-
let vars: Vec<_> = self
36-
.values
37-
.iter()
38-
.map(|&value| model.add(var().binary().obj(value as f64)))
39-
.collect();
42+
let mut vars = Vec::with_capacity(self.sizes.len());
43+
for i in 0..self.sizes.len() {
44+
vars.push(model.add(var().binary().obj(self.values[i] as f64)));
45+
}
4046

41-
let var_sizes = vars
42-
.iter()
43-
.zip(self.sizes.iter())
44-
.map(|(var, &size)| (var, size as f64));
45-
model.add(cons().le(self.capacity as f64).expr(var_sizes));
47+
let mut capacity_cons = cons().le(self.capacity as f64);
48+
for (i, var) in vars.iter().enumerate() {
49+
capacity_cons = capacity_cons.coef(var, self.sizes[i] as f64);
50+
}
51+
model.add(capacity_cons);
4652

4753
let solved_model = model.solve();
4854

4955
let sol = solved_model.best_sol().unwrap();
50-
let items: Vec<_> = vars
51-
.iter()
52-
.enumerate()
53-
.filter(|(_, v)| sol.val(v) > 1e-6)
54-
.map(|(i, _)| i)
55-
.collect();
56+
let mut items = vec![];
57+
for (i, var) in vars.iter().enumerate() {
58+
if sol.val(var) > 0.5 {
59+
items.push(i);
60+
}
61+
}
5662
let value = sol.obj_val();
57-
5863
KnapsackSolution { items, value }
5964
}
6065
}

0 commit comments

Comments
 (0)