Я бы сначала проверил длины actual
и expected
. Затем я бы протестировал дельту и выполнил обрезку за один цикл и за один шаг (Math.min(int, int)
может помочь). Например,
public boolean check(int[] expected, int[] actual, int maxValue, int delta) {
if (actual.length != expected.length) {
return false;
}
for (int i = 0; i < actual.length; ++i) {
if (Math.abs(expected[i] - Math.min(maxValue, actual[i])) > delta) {
return false;
}
}
return true;
}
Если вы используете Java 8+, вы можете уменьшить его до лямбды.
public boolean check(int[] expected, int[] actual, int maxValue, int delta) {
if (actual.length != expected.length) {
return false;
}
return IntStream.range(0, actual.length)
.noneMatch(i -> Math.abs(expected[i] - Math.min(maxValue, actual[i])) > delta);
}
И, наконец, (сложный) возврат в одну строку, например
public boolean check(int[] expected, int[] actual, int maxValue, int delta) {
return actual.length == expected.length && IntStream.range(0, actual.length)
.noneMatch(i -> Math.abs(expected[i] - Math.min(maxValue, actual[i])) > delta);
}