+- knapsack problem

9

1

Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.

Wikipedia for more information

For example you can be given a max weight of 15 and objects with value/masses as [5,2], [7,4] [1,1] and you would output [7,0,1] which is 7 [5 <value>, 2 <mass>] objects and 1 [1 <value>, 1 <mass>] object for a score of 36.

Rules

Input can be taken in any reasonable format

Output is also flexible format,

You may not use libraries that are non-standard. If you have to install or download any library to use it separate from the initial setup then it is not allowed

Objects may have negative mass and value (i.e -1,-1)

Optimal answers required

Winning

Shortest code wins

Negative mass and value?

This is a key part of this challenge. Lets say you have a object with items (mass, value) such as [4,3],[-1,-1] and a bag with capacity of 15. You could put 3 of the first ones and score 9 or put 4 of the first ones and one of the -1,-1 object for a score of 11.

Christopher

Posted 2018-04-13T17:37:39.030

Reputation: 3 428

sandbox – Christopher – 2018-04-13T17:37:55.553

Can we assume that no object will have non-positive mass? – HyperNeutrino – 2018-04-13T17:40:26.907

@HyperNeutrino one sec removing for edits – Christopher – 2018-04-13T17:46:01.750

They may have negative mass and value – Christopher – 2018-04-13T17:46:59.877

2Can we assume everything is an integer? Also, will we have to deal with cases like [[2, 1], [-1, -1]] where the total value can be made arbitrarily large? – None – 2018-04-13T17:59:23.627

@Mnemonic all ints, there will be no arbitralily large cases – Christopher – 2018-04-13T18:01:41.410

Related – Khuldraeseth na'Barya – 2018-04-13T18:12:04.363

I think that there is a mistake in the last paragraph: 4*4-1=15, which is more than 13. – Razvan Socol – 2018-04-13T18:56:33.407

5The title is misleading. Due to negative weights this is not the knapsack problem but a variation on the linear programming problem. – ngn – 2018-04-13T19:19:38.460

Again in the last paragraph: the score would be 11 (not 15) but the total mass would be 15, above the capacity which is 13. – Razvan Socol – 2018-04-14T04:44:09.570

@raz opps fixed – Christopher – 2018-04-14T10:54:21.803

Answers

2

Pyth, 18 bytes

h.MshMZfghQseMTy*F

Outputs as a list of [value, weight] pairs. Horrendously inefficient, but it is NP-complete.
Try it here

Explanation

h.MshMZfghQseMTy*F
               y*FQ  Get all sets with up to <capacity> of each item.
       fghQseMT      Choose the sets whose total weight fits in the bag.
 .MshMZ              Choose those with the highest value.
h                    Take the first.

user48543

Posted 2018-04-13T17:37:39.030

Reputation: