Friday, September 22, 2023
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 needs to be sorted in ascending order of values.

Assume there aren’t any duplicate integers within the array. The order of the integers within the enter array mustn’t matter.

Examples:

[1, 2, 3, 4]  ought to return [[1, 3], [2, 4]]
[4, 1, 2, 3]  also needs to 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

Choice 1:

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

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

Choice 2:

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

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

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

Take a look at instances to validate our resolution

import org.junit.Take a look at;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class Checks {
  @Take a look at
  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