Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading