我正在學習Comparator接口來解決分數揹包問題。行a和b中的兩個數組表示3個值 - 權重對 - (60,20),(100,50),(120,30)。比較器應該根據v [i]/w [i]的比值對arr []進行排序。但是,下面的代碼給了我奇怪的錯誤:ArrayIndexOutOfBoundsException對於我的Java比較器接口
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
我比較似乎是試圖訪問索引的ARR [] = 3,但我不能限制其索引的訪問。任何解決方案
這裏是我的代碼:
int[] v = {60, 100, 120}; // v: values. line a
int[] w = {20, 50, 30}; // w: weights. line b
int len = v.length;
Integer[] arr = new Integer[len];
for (int i=0; i<len; i++)
arr[i] = v[i]/w[i];
//sort arr[] based on the ratios of v[i]/w[i]
Arrays.sort(arr, new Comparator<Integer>() {
@Override public int compare(Integer o1, Integer o2) {
return Double.compare(v[o1]/w[o1], v[o2]/w[o2]);
}
});
double[] v_sorted = new double[len];
double[] w_sorted = new double[len];
for (int i = 0; i < len; ++i) {
v_sorted[i] = v[arr[i]];
w_sorted[i] = w[arr[i]];
}
哪裏是數組'v'或者是變量'v '在代碼中?我認爲你的意思是'values'而不是'v'和'weights'而不是'w'.如果你在那裏正確地使用它,那將是非常棒的...... – GOXR3PLUS