ArrayIndexOutOfRange的问题

时间:2017-03-07 17:14:17

标签: java arrays algorithm

  

我正在尝试实现这个伪代码:

     

ALGORITHM BruteForce(权重[1 ... N],值[1 ... N],A [1 ... N])   //为KP //输入找到最佳项目组合:   数组权重包含数组值包含的所有项的权重   使用以0s初始化的所有项目的数组A的值   生成位字符串//输出:最佳可能的项目组合   在背包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
  

以下是我的尝试:

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);

    }

}
  

我一直在使ArrayIndex超出范围。但我不知道为什么   A的长度设置为weights长度,因此不应该是任何长度   我心中的错误。我究竟做错了什么?这是一个算法   解决背包问题btw。以防万一有人熟悉   它会对这种算法提出任何批评。

     编辑:我改变了这个:

          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

1 个答案:

答案 0 :(得分:0)

在您的示例j = 3中 数组位置从0

开始
A[0]
A[1]
A[2]

您需要-1