Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- public static ExVariables sortedConsecutiveTwoRepeating(int[] a,
- final int startOfRange) {
- int low = startOfRange;
- int high = low + (a.length - 1);
- int x = low - 1;
- boolean foundX = false;
- for (int i = 0; i < a.length; i++) {
- if (a[i] > low) {
- if (foundX) {
- return new ExVariables(x, low);
- }
- x = low;
- foundX = true;
- }
- if (a[i] >= low) {
- low++;
- }
- }
- if (foundX) {
- return new ExVariables(x, high);
- } else {
- return new ExVariables(high - 1, high);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement