GLPK/Knapsack Problem

The knapsack problem is a classical packing problem from combinatorial optimization.

The knapsack problem can be defined as follows: given a set of $$N$$ items of size $$s_i$$ and profit $$p_i$$, select a subset of those items which fit into capacity $$c$$ and which maximize the collective profit of the chosen items:

The knapsack problem belongs to the class of NP-hard problems.

A usual way to solve knapsack problems is through dynamic programming (DP). The example below shows how to formulate the knapsack problem as a mixed-integer program (MIP) implemented in GMPL (MathProg).


 * 1) en.wikipedia.org offers the following definition:
 * 2) The knapsack problem or rucksack problem is a problem in combinatorial optimization:
 * 3) Given a set of items, each with a weight and a value, determine the number of each
 * 4) item to include in a collection so that the total weight is less than a given limit
 * 5) and the total value is as large as possible.
 * 6) This file shows how to model a knapsack problem in GMPL.
 * 1) This file shows how to model a knapsack problem in GMPL.

param c;
 * 1) Size of knapsack

set I, dimen 3;
 * 1) Items: index, size, profit

set J := setof{(i,s,p) in I} i;
 * 1) Indices

var a{J}, binary;
 * 1) Assignment

maximize obj : sum{(i,s,p) in I} p*a[i];

s.t. size : sum{(i,s,p) in I} s*a[i] <= c;

solve;

printf "The knapsack contains:\n"; printf {(i,s,p) in I: a[i] == 1} " %i", i; printf "\n";

data;

param c := 100;
 * 1) Size of the knapsack

set I := 1 10 10 2 10 10  3 15 15  4 20 20  5 20 20  6 24 24  7 24 24  8 50 50;
 * 1) Items: index, size, profit

end;

Now save and run this model using GLPSOL (1 second on an Intel Core i5 processor).

$ glpsol --math knapsack.mod

To yield:

The knapsack contains: 2 4 5 8