So my problem is a little bit like knapsnack problem but with a bit of difference. Let's say I went to shopping and I am obliged to buy things that meet the requirements or the closest I can get (over the requirement or lower). For a better explanation let's say I need to know how much items do I buy from each shopping item that brings me the closest to my requirements with at least one item each. For example my requirements are:
- Weight: 20 kg
- Price: 20 usd
- Calories: 300 kcal
and each item has a weight, price and calories with the possibility that any one of those can be 0:
- Item_1: { weight: 1kg, price: 0.5 usd, calories: 0 kcal, }
- Item_2: { weight: 3kg, price: 3 usd, calories: 70 kcal, }
I need to find the closest combination of n items that brings me close to my requirements (over it or lower than it as long as it is the closest)
I tried the knapsack problem and packing problem but with no luck.
----- Edit -----
As suggested let me clear some things, What I mean by closest is how many I should buy from each item to get as close as I can to the required weight, price and calories, as per example provided above I would need 6 from item_2 and 4 from item_1 meaning I would get a total of:
{ weight: 6 * 3 + 4 * 1 = 22 kg
price: 6 * 3 + 4 * 0.5 = 20 usd
calories: 6 * 70 + 4 * 0 = 420 kcal }
Which is (I think) the closest I can get to the requirements
While a solution might be possible using either a knapsack or linear programming solution, given your stated set of requirements, (i.e., minimize difference from target W, P, C and contains at least 1 of each product). I believe the simplest approach would be as follows:
The following code implements the above solution
Then given an input of the form:
Where first line contains objective W, P, C respectively and subsequent lines identify product options (W, P, c), then executing:
Yields: Weight= 33.9, Price= 38.5, Calories= 88.0 Product Qty: [1, 2, 3] # The qty of each product bought