Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.
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 FindMissing {
private FindMissing() {};
/**
* Takes an input a sorted array with two variables that repeat in the
* range. Remaining variable are consecutive. and returns two variables that repeats
*
* eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.
*
* @param a : the sorted array.
*/
/*
* Why is start needed ?
* If start is not given then if a1 is empty how do we know if missing numbers were
* [1, 2] or [4, 5] ??.
*/
public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {
if (a == null) throw new NullPointerException("a1 cannot be null. ");
int low = startOfRange;
// calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.
int high = startOfRange + (a.length - 1) + 2;
int i = 0;
boolean foundX = false;
int x = 0;
while (i < a.length) {
if (a[i] != low) {
if (foundX) {
return new Variables(x, low);
} else {
x = low;
foundX = true;
}
} else {
i++;
}
low++;
}
return new Variables(x, high);
}
public static void main(String[] args) {
// unsortedConsecutiveTwoMissing
int[] a6 = {1, 4};
System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));
// unsortedConsecutiveTwoMissing
int[] a7 = {-4, -1};
System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));
int[] a8 = {-4, -3, -2, -1};
System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));
int[] a9 = {5};
System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));
}
}
low
is initialized to an index in the array, but then it is compared to a value in the arrayif (a1[i] != low)
. This makes no sense... islow
an index, or a value? Can it possibly be both? \$\endgroup\$"x = 6 y = 6".equals(FindMissing.sortedConsecutiveTwoMissing(new int[]{5}, 4).toString())
\$\endgroup\$