Return the k elements of an array farthest from val
Method needs to return the k elements a[i] such that ABS(a[i] - val) are
the k largest evaluation. My code only works for integers greater than
val. It will fail if integers less than val. Could somebody just enlighten
me? Any help will be much appreciated!
public static int[] farthestK(int[] a, int val, int k) {
int[] b = new int[a.length];
for (int i = 0; i < b.length; i++) {
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[k];
int w = 0;
for (int i = b.length-1; i > b.length-k-1; i--) {
c[w] = b[i] + val;
w++;
}
return c;
}
test case:
@Test public void farthestKTest() {
int[] a = {-2, 4, -6, 7, 8, 14, 15};
int[] expected = {15, -6, 13, -2};
int[] actual = Selector.farthestK(a, 4, 4);
Assert.assertArrayEquals(expected, actual);
}
There was 1 failure:
1) farthestKTest(SelectorTest)
arrays first differed at element [1]; expected:<-6> but was:<14>
FAILURES!!!
Tests run: 1, Failures: 1
No comments:
Post a Comment