Question about expected behavior for knapsack constraint #1085
paulk-asert
started this conversation in
General
Replies: 1 comment 1 reply
Actually, the objective is considered within the constraint, for filtering, but you still have to define it as a goal.
I don't know Groovy, but it seems that you are looking the first solution only. In java your code would look like: int[] energies = {1, 5, 10, 15, 17}; // energies
int[] weights = {1, 2, 3, 5, 6};
int nos = energies.length;
Model model = new Model("Knapsack");
// occurrence of each item
IntVar[] counts = new IntVar[nos];
for (int i = 0; i < nos; i++) {
counts[i] = model.intVar("counts_" + (i + 1), 0, 10);
}
// objective variable
IntVar totalValue = model.intVar("power", 0, 100000);
IntVar scalar = model.intVar("weight", 0, 10);
model.knapsack(counts, scalar, totalValue, weights, energies).post();
model.setObjective(MAXIMIZE, totalValue);
if(model.getSolver().solve()){
System.out.printf("Power : %s, ", totalValue.getValue());
System.out.printf("Objects : %s\n", Arrays.toString(counts));
}Running this looks (and stops) for the first solution. |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Hi, I was doing a little example of a knapsack problem:
When using the knapsack constraint, it seems I still have to set a MAXIMIZE objective? Or am I doing something wrong?
My code is here:
https://github.com/paulk-asert/groovy-knapsack/blob/main/src/main/groovy/choco/Builtin.groovy
When I run I get:
If I leave out the
setObjective(MAXIMIZE, total)I get:I would have thought that objective would be part of the knapsack constraint?
Also, I have a version coding the constraints "long-hand" with some explicit search hints:
https://github.com/paulk-asert/groovy-knapsack/blob/main/src/main/groovy/choco/Constraints.groovy
Running this gives the expected maximum value:
Do I need extra search hints for the knapsack constraint too?
All reactions