Home > Back-end >  Java: Pairing values from 1D arrays to 2D arrays while excluding corresponding values
Java: Pairing values from 1D arrays to 2D arrays while excluding corresponding values

Time:09-14

Given arr1: [0, 1, -1, 3, -1],

and arr2: [15, 15, 10, 20, 20],

how can I create this 2D array:

[[0, 15], [1, 15], [3, 20]]

You'll notice that I'm trying to exclude -1 values and their corresponding values in the same indices between both arrays.

I'm thinking create a copy of arr1 that excludes -1 values but I'm not sure how to go from there.

CodePudding user response:

you can try:

public static void main(String[] args) {
        int[] arr1 = new int[]{0, 1, -1, 3, -1};
        int[] arr2 = new int[]{15, 15, 10, 20, 20};

        long length1 = Arrays.stream(arr1).filter(i -> i != -1).count();
        long length2 = Arrays.stream(arr2).filter(i -> i != -1).count();

        int index = 0;
        int resultLength = Math.toIntExact(Math.min(length1, length2));
        int[][] result = new int[resultLength][2];
        for (int i = 0; i < arr1.length; i  ) {
            if (arr1[i] != -1 && arr2[i] != -1) {
                result[index][0] = arr1[i];
                result[index][1] = arr2[i];
                index   ;
            }
        }

        // Result: [[0, 15], [1, 15], [3, 20]]
        System.out.println(Arrays.deepToString(result));
    }

CodePudding user response:

Assuming your arrays have always the same length and both arrays could contain negative values, try something like below:

int[] arr1 = {0, 1, -1, 3, -1};

int[] arr2 = {15, 15, 10, 20, 20};

int[][] result = IntStream.range(0, arr1.length)
                          .filter(i -> arr1[i] >= 0 && arr2[i] > 0)
                          .mapToObj(i -> new int[]{arr1[i], arr2[i]})
                          .toArray(int[][]::new);

System.out.println(Arrays.deepToString(result));

CodePudding user response:

Assuming you are looking for excluding values which are negative from arr1, then below is one of option:

int[] arr1 = { 0, 1, -1, 3, -1 };
int[] arr2 = { 15, 15, 10, 20, 20 };

int arr3[][] = new int[(int) Arrays.stream(arr1).filter(x -> x >= 0).count()][2];
int k = 0, j = 0;
for (int i = 0; i < arr1.length; i  ) {
    if (arr1[i] >= 0) {
        arr3[j][k  ] = arr1[i];
        arr3[j][k--] = arr2[i];
        j  ;
    }
}

System.out.println(Arrays.deepToString(arr3));

CodePudding user response:

Just iterate over first array and pair values by indices skipping -1 element.

  • Related