Fill the third array by adding the elements of the first and second array

Wrote the dumbest code in the hope that it will work

        String[] arr1 = listLetters.get(0);//[a,b,c]
        String[] arr2 = listLetters.get(1);//[d,e,f]

        //result must be [ad,ae,af,bd,be...]
        String[] result = new String[arr1.length* arr2.length];
        for (int k=0; k< result.length; k++){
        for (int i =0; i<arr1.length; i++){
            for (int j=0; j< arr2.length; j++){
                    result[k] = arr1[i]+arr2[j];
                }
            }
        }
        System.out.println(Arrays.toString(result));
    }

As a result, output: enter image description here

How to fix it?

>Solution :

You don’t need the very first for-loop, it causes all the values in the resulting array to be overwritten multiple times.

Instead, you need to declare the index k of the resulting array outside the nested loop that generates the Cartesian product of the two given arrays. k should be incremented at each iteration step of the inner loop.

int k = 0;
for (int i = 0; i < arr1.length; i++) {
    for (int j = 0; j < arr2.length; j++) {
        result[k++] = arr1[i] + arr2[j];
    }
}

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

Output:

[ad, ae, af, bd, be, bf, cd, ce, cf]

Leave a Reply