Suggestions for cleanup and optimization request.
This question is a follow-up question on this post.
Lets assume the range of
1, 2, 3, 4.
This function takes in an array of repeated elements, [1,1,4,4]
and the output is [2, 3]
.
The question marked as duplicate takes an input of [1, 4]
and output is [2, 3]
.
While output is same, the input differs.
Please make a note of this difference between two questions causing confusion.
final class Variables {
private final int x;
private final int y;
Variables(int x2, int y2) {
this.x = x2;
this.y = y2;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override public String toString() {
return "x = " + x + " y = " + y;
}
}
public final class FindMissingRepeating {
/**
* Takes an input a sorted array with only two variables that repeat once. in the
* range. and returns two variables that are missing.
*
* If any of the above condition does not hold true at input the results are unpredictable.
*
* Example of input:
* range: 1, 2, 3, 4
* input array [1, 1, 4, 4]
* the variables should contain 2 missing elements ie 2 and 3
*
* @param a : the sorted array.
*/
public static Variables sortedConsecutiveTwoRepeating (int[] a, int startOfRange) {
if (a == null) throw new NullPointerException("a1 cannot be null. ");
int low = startOfRange;
int high = low + (a.length - 1);
int x = 0;
int i = 0;
boolean foundX = false;
while (i < a.length) {
if (a[i] < low) {
i++;
} else {
if (a[i] > low) {
if (foundX) {
return new Variables(x, low);
} else {
x = low;
foundX = true;
}
}
low++;
i++;
}
}
int val = foundX ? x : high - 1;
return new Variables(val, high);
}
public static void main(String[] args) {
int[] ar1 = {1, 2, 2, 3, 4, 4, 5};
Variables v1 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar1, 1);
System.out.println("Expected x = 6, y = 7 " + v1);
int[] ar2 = {2, 2, 4, 4, 5, 6, 7};
Variables v2 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar2, 1);
System.out.println("Expected x = 1, y = 3 " + v2);
int[] ar3 = {3, 3, 4, 4, 5, 6, 7};
Variables v3 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar3, 1);
System.out.println("Expected x = 1, y = 2 " + v3);
int[] ar4 = {1, 3, 3, 4, 4, 6, 7};
Variables v4 = FindMissingRepeating.sortedConsecutiveTwoRepeating (ar4, 1);
System.out.println("Expected x = 2, y = 5 " + v4);
}
}