[ojAlgo-user] Knapsack problem with binary variables
Mathematics, linear algebra and optimisation
Brought to you by:
apete
From: Luke L. <luk...@gm...> - 2010-04-11 21:07:58
|
I am trying to solve a simple knapsack problem (maximise value given weight limit) with ojalgo. See code below. The code works as I would expected when var[i] are not set to integers. I.e. the result is "OPTIMAL (0) { 1.0, 0.25, 3.0, 0.0, 0.0, 0.75 }" which I interpret as meaning "take one unit of item 0 and 0.25 of item 1". I want to restrict var[i] to being 0 or 1. But when I uncomment the line "vars[i].setInteger(true);", I get "OPTIMAL (1) { 0.0, 0.0, 0.0, 3.0, 0.0, 1.0, 1.0 }". I was expecting "OPTIMAL (0) { 1.0, 0.0, 0..." i.e. "take one unit of item 0 and none of item 1". Am I doing something wrong here? ......................................................................................................................................... package knapsack; import static org.ojalgo.constant.BigMath.*; import java.math.BigDecimal; import org.ojalgo.optimisation.*; import org.ojalgo.optimisation.OptimisationSolver.Result; import org.ojalgo.optimisation.linear.LinearExpressionsModel; public class Knapsack { static class Item{ final BigDecimal value; final BigDecimal weight; public Item(int value, int weight) { this.value = new BigDecimal(value); this.weight = new BigDecimal(weight); } } public static void main(String[] args) { BigDecimal maxWeight = new BigDecimal(3); Item[] items = {new Item(20, 2), new Item(30, 4)}; Variable[] vars = new Variable[items.length]; for(int i =0; i < vars.length; i++){ vars[i] = new Variable(String.valueOf(i)); //vars[i].setInteger(true); vars[i].upper(ONE).lower(ZERO); vars[i].setContributionWeight(items[i].value); } LinearExpressionsModel model = new LinearExpressionsModel(vars); Expression totalWeight = model.addEmptyLinearExpression("total weight"); for(int i =0; i < items.length; i++){ totalWeight.setLinearFactor(i, items[i].weight); } totalWeight.setUpperLimit(maxWeight); totalWeight.setLowerLimit(ZERO); System.out.println(totalWeight); model.maximise(); OptimisationSolver solver = model.getDefaultSolver(); Result result = solver.solve(); System.out.println(result); System.out.println(model.maximise()); System.out.println(model.minimise()); } } |