Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add backtracking features in KnapsackUnbounded.java #278

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ public static int unboundedKnapsackSpaceEfficient(int maxWeight, int[] W, int[]
// the best possible value for each knapsack weight
int[] DP = new int[maxWeight + 1];

// 2D DPMatrix for backtracking
int[][] DPMatrix = new int[N + 1][maxWeight + 1];
int maxIndex = 0;

// Consider all possible knapsack sizes
for (int sz = 1; sz <= maxWeight; sz++) {

Expand All @@ -74,16 +78,54 @@ public static int unboundedKnapsackSpaceEfficient(int maxWeight, int[] W, int[]
// First check that we can include this item (we can't include it if
// it's too heavy for our knapsack). Assumming it fits inside the
// knapsack check if including this element would be profitable.
if (sz - W[i] >= 0 && DP[sz - W[i]] + V[i] > DP[sz]) DP[sz] = DP[sz - W[i]] + V[i];
if (sz - W[i] >= 0 && DP[sz - W[i]] + V[i] > DP[sz]) {
DP[sz] = DP[sz - W[i]] + V[i];
DPMatrix[i][sz] = DP[sz - W[i]] + V[i];
maxIndex = i;
}
}
}

// Array to store quantity for each item
int [] quantity = new int[N + 1];

int value1 = DPMatrix[maxIndex][maxWeight];

for(int k = maxWeight; k > 1;k--) {
int value2 = DPMatrix[maxIndex][k - 1];

if((value1 - value2) == value1) {
continue;
}
else if(value1 == value2){
for(int i = 0; i < N ; i++) {
if (value1 == V[i]) {
quantity[i] = quantity[i] + 1;
}
}
}
else {
int diff = value1 - value2;
for(int i = 0; i < N ; i++) {
if (diff == V[i]) {
quantity[i] = quantity[i] + 1;
value1 = value2;
}
}
}
}

// Display item weight, value and quantity
System.out.println("Item\tWeight\tValue\tQuantity");
for(int i = 0; i < quantity.length - 1;i++) {
System.out.println((i+1) + "\t" + W[i] + "\t" + V[i] + "\t" + quantity[i]);
}

// Return the best value achievable
return DP[maxWeight];
return DPMatrix[maxIndex][maxWeight];
}

public static void main(String[] args) {

int[] W = {3, 6, 2};
int[] V = {5, 20, 3};
int knapsackValue = unboundedKnapsackSpaceEfficient(10, W, V);
Expand Down