I was playing around with the new KnapsackSolve function in Mathematica 11 and came across something odd that I don't understand. Perhaps someone could shed some light on this for me. Here's my dataset:

data = <|"two" -> {1, 2, 1}, "three" -> {1, 3, 1}, "four" -> {1, 4, 1}|>

When I call KnapsackSolve for various target values:

<|"two" -> 1, "three" -> 0, "four" -> 0|>
<|"two" -> 1, "three" -> 0, "four" -> 0|>
<|"two" -> 0, "three" -> 1, "four" -> 0|>
<|"two" -> 1, "three" -> 1, "four" -> 0|>

I was expecting 2 to give "two" - correct but 3 and 4 give unexpected answers, then 5 gives me "two" and "three".

I've set the costs to be all maxcounts all be to 1 and payoffs to be 1 also. What am I doing wrong?


You are trying to maximize c1+c2+c3 subject to 2c1+3c2+4c2<=n, where all variables are either 0 or 1.

For n=2 there is only one answer, c1=1,c2=0,c3=0.

For n=3 there are two answers, c1=1,c2=0,c3=0 as given, or c1=0,c2=1,c3=0.

For n=4 there are three answers, c1=0,c2=1,c3=0 as given, or c1=1,c2=0,c3=0, or c1=0,c2=0,c3=1.

For n=5 there is only one answer c1=1,c2=1,c3=0.

  • $\begingroup$ I understand, so I'm only getting the first answer back that fulfils the criteria rather than the complete set of answers then. It's not clear from the documentation that all results are not returned - but then again all of the examples only return a single set! $\endgroup$ – FractalDoctor Nov 30 '16 at 20:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.