Melkweg
Melkweg

Reputation: 29

How can I merge 2 arrays in 1 loop?

I was told to make

void mergeArrays(int[] ar1 , int[] ar2)

For an input like this:

int[] ar1 = {1,2,3,4}
int[] ar2 = {5,6,7,8}

This is my code :

 public static void mergeArray(int[] ar1 , int[] ar2)    {
        int[] res = new int[ar1.length+ar2.length];
        int counter = 0;
        for(int a = 0; a<ar1.length; a++)
        {
            res[a] = ar1[a];
            counter++;
        }
        for(int b = 0; b<ar2.length; b++)
        {
            res[counter++] = ar2[b];
        }
        for(int temp = 0; temp<res.length;temp++)
        {
            System.out.print(res[temp]+" ");
        }

Output 12345678.

This is done using 2 loops. Now, how can I do it using a single loop?

Upvotes: 2

Views: 2280

Answers (2)

haba713
haba713

Reputation: 2687

Different length arrays

    int[] result = new int[ar1.length + ar2.length];
    for(int i = 0; i < result.length; i++) {
        result[i] = i < ar1.length ? ar1[i] : ar2[i - ar1.length]; // comparison
    }

Equal length arrays

    int[] result = new int[ar1.length + ar2.length];
    for(int i = 0; i < ar1.length; i++) {
        result[i] = ar1[i];              // no
        result[ar1.length + i] = ar2[i]; // comparison      
    }

See (and execute) the full implementation here.

Upvotes: 1

McRist
McRist

Reputation: 1758

Yes, you can do it in one loop,

        int len = arr1.length + arr2.length;
        int[] res = new int[len];

        for(int i=0, j=0; i<len; i++) {
            if(i<arr1.length){
                res[i] = arr1[i];
            }else{
                res[i] = arr2[j];
                j++;

            }
        }

This will work also, when both arrays are of different length.

Upvotes: 7

Related Questions