LED Fantom - 6 months ago 32

Java Question

I am learning about Comparator interface to solve a fractional knapsack problem. The two arrays in line a and b indicate 3 value-weight pairs - (60, 20), (100, 50), (120, 30). The Comparator is supposed to sort arr[] based on the ratios of v[i]/w[i]. However, The following code gives me weird error:

`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3`

My Comparator seems to be trying to access index=3 of arr[], but I can't limit its access of indices. Any solutions?

Here is my code:

`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]];

}

Answer

The problem is that you are trying to sort indexes, as represented by `o1`

and `o2`

in your comparator code, but your `arr`

contains pre-computed ratios.

Filling the array with numbers `0`

through `len-1`

, inclusive, will solve the problem:

```
for (int i=0; i<len; i++)
arr[i] = i;
```

Now the comparator will get a pair of indexes, and compare ratios of `v[...]`

to `w[...]`

based on them.