配列内の特定の値より大きい値の数を見つけるためにこのメソッドを作成しました。正の整数を持つ配列で機能しますが、このテスト ケースを試してみると失敗しました。
public static int numGreater(int[] a, int val) {
if (a == null || a.length == 0) {
throw new IllegalArgumentException();
}
int[] copy = Arrays.copyOf(a, a.length);
Arrays.sort(copy);
int answer = 0;
int nearest = copy[0];
for (int i = 0; i < copy.length; i++) {
if (Math.abs(nearest - val) > Math.abs(copy[i] - val)) {
nearest = copy[i];
answer = (copy.length - 1) - i;
}
}
return answer;
}
JUnit で実行したテスト ケースを次に示します。
int z[] = {-5,-2,0,4,8,15,50};
@Test public void numGreaterTest1() {
Assert.assertEquals(7, Selector.numGreater(z, -99));
}
私が間違っていた場所についてのアイデアはありますか?