I am trying to implement this pseudocode:
ALGORITHM BruteForce (Weights [1 ... N], Values [1 ... N], A[1...N]) //Finds the best possible combination of items for the KP //Input: Array Weights contains the weights of all items Array Values contains the values of all items Array A initialized with 0s is used to generate the bit strings //Output: Best possible combination of items in the knapsack bestChoice [1 .. N]
for i = 1 to 2^n do
j = n
tempWeight = 0
tempValue = 0
while ( A[j] != 0 and j > 0)
A[j] = 0
j = j–1
A[j] = 1
for k = 1 to n do
if (A[k] = 1) then
tempWeight = tempWeight + Weights[k]
tempValue = tempValue + Values[k]
if ((tempValue > bestValue) AND (tempWeight <= Capacity)) then
bestValue = tempValue
bestWeight = tempWeight
bestChoice = A
return bestChoice
Here is my try at it:
public class BruteForce {
public static final int CAPACITY = 50;
public static double[] bruteForce(double[] weights, double[] values, double[] A) {
int n = weights.length;
int j;
double[] bestChoice = null;
double tempWeight;
double tempValue;
double bestValue = 0;
double bestWeight = 0;
for (int i = 1; i < Math.pow(2, n); i++) {
j = n;
tempWeight = 0;
tempValue = 0;
// Here is the issue of ArrayIndexOutOfBounds: 3
while (A[j] != 0 && j > 0) {
A[j] = 0;
j = j - 1;
}
A[j] = 1;
for (int k = 1; k < n; k++) {
if (A[k] == 1) {
tempWeight = tempWeight + weights[k];
tempValue = tempValue + values[k];
}
}
if ((tempValue > bestValue) && (tempWeight <= CAPACITY)) {
bestValue = tempValue;
bestWeight = tempWeight;
}
bestChoice = A;
}
return bestChoice;
}
public static void main(String[] args) {
double[] weights = { 10, 20, 15 };
double[] values = { 5, 10, 30 };
double[] A = new double[weights.length];
BruteForce.bruteForce(weights, values, A);
}
}
I keep on getting an ArrayIndex out of bounds. But I don't know why
A's length is set toweightslength so there shouldn't be any error in my mind. What am I doing wrong? This is an algorithm for solving the knapsack problem btw. Just in case anyone is familiar with it and would offer any critiquing of this algorithm.EDIT: I've changed this:
while (A[j-1] != 0 && j > 0) { A[j] = 0; // This would need to be changed too then right? j = j - 1; } A[j-1] = 1; // This changed
j = n;. That's equivalent toj = weights.length;You then useA[j], andAhas the same length asweights. So that will always fail. Arrays are zero-indexed in Java.2ntoMath.pow(2,n)meaning 2^n. Is that what the algorithm meant ?int j = n - 1;to avoid the ArrayOutOfBoundException. EDIT : It's rather the translation from the [1..N] in pseudocode to [0..n[ that breaks.