A robber burgles a butcher's shop, where he can select from some items. He knows the weights and prices of each items. Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after cutting that is proportional to the original price by the ratio of masses. That means: half of an item has half the price of the original.

This is the item list in the butcher's:

Table of potential knapsack items

Item

Weight (kg)

Price (Value)

beef

3.8

36

pork

5.4

43

ham

3.6

90

greaves

2.4

45

flitch

4.0

30

brawn

2.5

56

welt

3.7

67

salami

3.0

95

sausage

5.9

98

Knapsack

<=15 kg

?

Which items does the robber carry in his knapsack so that their total weight does not exceed 15 kg, and their total value is maximised?

> knap items 15.0;;
Take all salami
Take all ham
Take all brawn
Take all greaves
Take 3.50kg of welt
Total value of swag is £349.38

Should your burglar be greedy, he may bring a bigger bag.

> knap items 100.0;;
Take all salami
Take all ham
Take all brawn
Take all greaves
Take all welt
Take all sausage
Take all beef
Take all pork
Take all flitch
Everything taken! Total value of swag is £560.00; Total weight of bag is 34.30kg

: knapsack ( --) (items) dup #items dup 0 ?do i items (items) i th ! loop sort begin \ use the sorted array dup weight@ left <= \ still room in the knapsack? while ." Take all of the " dup .item \ take all of the item left over weight@ - to left cell+ \ adjust knapsack, increment item repeat left 100 * dup \ so how much is left? \ if room, take as much as possible if ." Take " . ." grams of the " .item else drop drop then;

Take all of the salami (3.000000 kg) worth $95.000000
Take all of the ham (3.600000 kg) worth $90.000000
Take all of the brawn (2.500000 kg) worth $56.000000
Take all of the greaves (2.400000 kg) worth $45.000000
Take (3.500000 kg) of the welt worth $63.378378
Total value of a full knapsack is $349.378378

// set the member with name "inKnapsack" by all items:privatevoid setInKnapsackByAll(double inKnapsack){for(Item item : itemList) item.setInKnapsack(inKnapsack);}

// set the data members of class in the state of starting the calculation:protectedvoid setInitialStateForCalculation(){ setInKnapsackByAll(-0.0001); calculated =false; profit =0.0; solutionWeight =0.0;}

The problem is solved by sorting the original table by price to weight ratio, finding the accumlated weight, and the index of the item which exedes the carrying capacity (overN)
The output is then all items prior to this one, along with that item corrected for it's excess weighter (overW)

We might as well leave this one to the experts by setting it up as a
linear programming problem and handing it off to an external library (which will be either lpsolve or
glpk depending on the
run-time system configuration).