3

I came cross Knapsack problem, where the maximum number of multiple items from a set of items need to be placed into one bin by minimizing the cost. I am able to solve the optimization problem in CPLEX.

However, I am finding difficulties in implementing in CPLEX, when the problem consists of two bins (with different capacities).

The problem:

Bin = [B1, B2] 
Capacity = [7,5]

Item = [I1, I2, I3, I4]
Weight = [6,3,1,4]
Price = [2,8,2,4]

The objective is to place the maximum number of items and to minimize the total price.

How can I implement this objective problem in CPLEX?

Below is my code snippet:

// ITEMS
int n=4; // no of items
range items = 1..n; // range of items
int p[items] = [2,8,2,6]; //price
int w[items] = [6,3,1,4]; //weight

// BINS
int m=2; // no of bins
range bins=1..m; // range of bin
int capacity[bins] = [7,5]; // capacity of each bin

dvar boolean x[items][bins]; 

// model ; max the profit
maximize sum(i in items, j in bins) p[i]*x[i][j];

subject to {
    forall (j in bins)
        cons1 : sum(i in items) w[i]*x[i][j] <= capacity[j];
    forall (i in items)
        cons2 : sum(j in bins) x[i][j] == 1;    
} 

-Thanks

2 Answers2

2

If you add

assert sum(i in items) w[i]<=sum(b in bins) capacity[b];

then this assert is violated and this explains why you do not get a solution. You do not have enough bin capacity.

But then if you turn:

int capacity[bins] = [7,5]; // capacity of each bin

into

int capacity[bins] = [7,7]; // capacity of each bin

then you'll get a solution.

halfer
  • 19,824
  • 17
  • 99
  • 186
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15
0

You can find a knapsack example in CPLEX_Studio1271\opl\examples\opl\knapsack.

halfer
  • 19,824
  • 17
  • 99
  • 186
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15
  • Yes, I have gone through that example. That Knapsack example consists of one bin and multiple items. But I am trying to modify that for multiple bins (with different capacities) and multiple items. So far I am unable to get any hint to proceed. -Thanks – CHINMAYA DEHURY Sep 08 '17 at 03:28