Wednesday, February 21, 2024
HomeSoftware EngineeringThe Distinction of two in Java

The Distinction of two in Java


The problem

The target is to return all pairs of integers from a given array of integers which have a distinction of two.

The ensuing array must be sorted in ascending order of values.

Assume there are not any duplicate integers within the array. The order of the integers within the enter array shouldn’t matter.

Examples:

[1, 2, 3, 4]  ought to return [[1, 3], [2, 4]]
[4, 1, 2, 3]  must also return [[1, 3], [2, 4]]
[1, 23, 3, 4, 7] ought to return [[1, 3]]
[4, 3, 1, 5, 6] ought to return [[1, 3], [3, 5], [4, 6]]

The answer in Java code

Possibility 1:

import java.util.*;
import java.util.stream.*;

public class Problem {
  public static int[][] twosDifference(int[] a) {
    var s = Arrays.stream(a).boxed().gather(Collectors.toSet());
    return Arrays.stream(a).boxed().filter(x -> s.comprises(x + 2)).sorted().map(x -> new int[]{x, x + 2}).toArray(int[][]::new);
  }
}

Possibility 2:

import static java.util.Arrays.*;
import java.util.*;

public class Problem {
  public static int[][] twosDifference(int[] array) {
    type(array);
    last Checklist<int[]> consequence = new LinkedList<>();
    for (int quantity : array) {
      int search = quantity - 2;
      if (binarySearch(array, search) >= 0) {
        consequence.add(new int[]{search, quantity});
      }
    }
    return consequence.toArray(new int[][] {});
  }
}

Possibility 3:

import static java.util.stream.IntStream.of;
import static org.apache.commons.lang3.ArrayUtils.comprises;

interface Problem {
  static int[][] twosDifference(int[] array) {
    return of(array).filter(i -> comprises(array, i + 2)).sorted().mapToObj(i -> new int[]{i, i + 2}).toArray(int[][]::new);
  }
}

Check circumstances to validate our resolution

import org.junit.Check;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class Assessments {
  @Check
  public void sample_tests() {
    assertArrayEquals(
      new int[][]{{1, 3}, {2, 4}},
      Problem.twosDifference(new int[]{1, 2, 3, 4})
    );
    assertArrayEquals(
      new int[][]{{1, 3}, {4, 6}},
      Problem.twosDifference(new int[]{1, 3, 4, 6})
    );
  }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments