Java ArrayIndexOutOfRange的问题
我正在尝试实现以下伪代码: 算法暴力(权重[1…N],值[1…N],A[1…N]) //查找KP//输入项的最佳可能组合: 数组权重包含数组值包含的所有项的权重 使用0初始化的数组的所有项的值用于 生成位字符串//输出:项目的最佳组合 背包里的最佳选择[1..N]Java ArrayIndexOutOfRange的问题,java,arrays,algorithm,Java,Arrays,Algorithm,我正在尝试实现以下伪代码: 算法暴力(权重[1…N],值[1…N],A[1…N]) //查找KP//输入项的最佳可能组合: 数组权重包含数组值包含的所有项的权重 使用0初始化的数组的所有项的值用于 生成位字符串//输出:项目的最佳组合 背包里的最佳选择[1..N] 在您的示例中,j=3 数组位置从0开始 A[0] A[1] A[2] 你需要一个-1看看这行j=n。这相当于j=weights.length然后使用A[j],并且A与权重具有相同的长度。因此,这将永远失败。数组在Java中是零索引的
在您的示例中,
j=3
数组位置从
0开始
A[0]
A[1]
A[2]
你需要一个-1
看看这行j=n代码>。这相当于j=weights.length
然后使用A[j]
,并且A
与权重具有相同的长度。因此,这将永远失败。数组在Java中是零索引的。您将2n
转换为Math.pow(2,n)
表示2^n。这就是算法的意思吗?是的。当我复制伪代码时,它消除了^。我已经更新了问题。谢谢你指出这一点。你误解了乔恩·斯基特的观点。你应该javeintj=n-1代码>以避免ArrayOutOfBoundException。编辑:这是从伪代码中的[1..N]到[0..N]的转换。啊,现在我明白了。谢谢。所以我不能从数组的末尾开始。你是说什么?我必须从头到尾迭代?不,你只需要做j=N-1。你介意检查我的编辑,看看我是否正确实现了它吗?
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);
}
}
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
A[0]
A[1]
A[2]