Definition: Given a set of items, each with a weight and a value, determine the items to include in a collection so that the total value is as large as possible and the total weight is less than a given limit. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most useful items.
Example: 5 items with weights, values and limit as given.
In Excel this problem looks as follows:
1. First, we declare five variables of type Double with names limit, weight, value, totalWeight and maximumValue.
Dim limit As Double, weight As Double, value As Double, totalWeight As Double, maximumValue As Double2. Next, we declare five variables of type Integer with with names i, j, k, l, m.
Dim i, j, k, l, m As Integer3. We initialize two variables. We initialize the variable limit with the value of cell D6. We initialize the variable maximumValue with value 0.
limit = Range("D6").value4. Next, we check each possible solution. We can either include an item (1) or leave it out (0). We start 5 For Next loops. One for each item.
maximumValue = 0
For i = 0 To 15. We calculate the weight and the value of a possible solution.
For j = 0 To 1
For k = 0 To 1
For l = 0 To 1
For m = 0 To 1
weight = 12 * i + 2 * j + 1 * k + 1 * l + 4 * m6. Only if value is higher than maximumValue and weight is lower than limit, we've found a new better solution.
value = 4 * i + 2 * j + 2 * k + 1 * l + 10 * m
If value > maximumValue And weight <= limit Then7. If true, we write the new solution to row 4, weight to totalWeight and value to maximumValue.
Range("B4").value = i8. Don't forget to close the If statement.
Range("C4").value = j
Range("D4").value = k
Range("E4").value = l
Range("F4").value = m
totalWeight = weight
maximumValue = value
End If9. Don't forget to close the 5 For Next loops.
Next mExcel VBA checks each possible solution this way and as a result the optimal solution will appear in row 4. Remember, 1 means we include an item, 0 means we leave it out.
Next l
Next k
Next j
Next i
10. Finally, write totalWeight and maximumValue of the optimal solution to respectively cell B6 and B8.
Range("B6").value = totalWeight11. Test the program.
Range("B8").value = maximumValue
Result:
Conclusion: it's optimal to include the last four items with a maximum value of 15. This solution with a total weight of 2 + 1 + 1 + 4 = 8 does not exceed the limit of 15.
Note: by making the weights and values variable you can solve any knapsack problem of this size (see downloadable Excel file)..