Implementation of the 0-1 (binary) Knapsack Problem
Technically an NP-Hard problem, so this solution doesn't scale for large values of the Knapsack Capacity
w is the current max weight of the knapsack (goes from 0 to W, the actual max weight of the knapsack)
- If wi>W, the item it too heavy to fit in the knapsack, so we copy the value from row above:
OPT(i-1,w)
- If the item CAN fit there are 2 cases
A slightly different version of the algorithm, but the point is the final loop that recovers the items from the keep array
This program runs on 5 items with 2 different weight capacities: 11 and 10solveKnapsack()
populates the memoization table & finds the maximum weight possiblememoizationTable
is filled with-1
to distinguish from completed rows- Then 0th row is filled with
0
memoizationTable
is printed usingprintTable()
after each row is completed
findOptimalKnapsackContents()
is called aftersolveKnapsack()
to see what items were actually added- The ID or name of an Item is its array index
- Must be non-negative integer weights
- Run with different items by changing arrays for
values
,weights
&numberOfItems
There is no error checking between those 3 fields, so hard-code them into the constructor
verifyCorrectArrayLength()
can be used to see if the array lengths matchnumberOfItems
, but it's not enforced - View output with fixed-width font for columns to line up (configure your IDE or copy to new document)
- Arrays are indexed from 1 to make human readable
- Put a 0 as the 1st element of
values
andweights
memoizationTable
andchosenItems
are both initialized to dimensions[numberOfItems+1][knapsackWeightCapacity+1]
to keep it indexed from 1- Pseudocode has a step to set all values in 0th row to 0. Not needed since Java initialized the entire 2D array to 0's
findWidestNumberInTable()
,findWidestElementInList()
andleftPad()
are all helper methods used byprintTable()
printTable()
is pretty fancy & prints padding spaces to the left of numbers so the columns line up. It looks nicer, but doesn't have to be that complicatedsolveKnapsack()
populates memoization table & addstrue
to the corresponding cell inchosenItems
matrix when an item is addedfindOptimalKnapsackContents()
works backwards from the bottom right corner of thechosenItems
matrix- A
true
inchosenItems
means that an item was added to get that max value when calculatingmemoizationTable
,false
means it just copied the value from the row above - Start with
currentCapacity=knapsackWeightCapacity
i
goes fromnumberOfItems
down to 1- If a value is
true
, we included that item in the knapsack so output the item @ rowi
- Since we included an Item, subtract its weight from
currentCapacity
(currentCapacity -= weights[i] -= weights[i]
)
This will move thecurrentCapacity
left some number of columns - Continue until it reaches the 1st row
- Done
- A