Kale
Kale

Reputation: 9

Is there a Java technique to solve duplicate loops in a class?

I recently submitted this code as part of a coding challenge online, as part of my feedback I was told that parts of my code could be improved to fit "good practice". I have tried to reduce the amount of lines however I wasn't given any tips, I am still unsure how to improve. I hope I can get some assistance.

public class ArrayChecker {
  public boolean check(int[] expected, int[] actual, int maxValue, int delta) {
    // Clip 'too large' values
    for (int i = 0; i < actual.length; ++i) {
      if (actual[i] > maxValue) {
        actual[i] = maxValue;
      }
    }

    // Check for length differences
    if (actual.length != expected.length) {
      return false;
    }

    // Check that each entry is within the expected +/- delta
    for (int i = 0; i < actual.length; ++i) {
      if (Math.abs(expected[i] - actual[i]) > delta) {
        return false;
      }
    }

    return true;
  }
}

Upvotes: 0

Views: 77

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201477

I would first check the lengths of actual and expected. Then, I would test the delta and perform the clipping in one loop and with one step (Math.min(int, int) can help). Like,

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;
}

If using Java 8+ you can reduce that to a lambda.

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);
 }

And finally, a (complex) one line return, like

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);
}

Upvotes: 1

Related Questions