Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix two arrays in Java?

Tags:

java

arrays

I have some String[] arrays, for example:

['a1', 'a2']
['b1', 'b2', 'b3', 'b4']
['c1']

How can I mix them, so that I get ['a1', 'b1', 'c1', 'a2', 'b2', 'b3', 'b4'] (0 element of a, then b, c, 1 element of a, b, c and so on)? Thanks

More accurately the resulting array must consist of the first value of the first array, then the first value of the second array, ..., the first value of the last array, the second value of the first array, ..., the second value of the last array, ..., the last value of the biggest array. If arrays are not of the same size, the smaller ones just aren't being taken into account.

Here's an illustration:

a1 a2 a3 a4
b1 b2 b3 b4 b5 b6 b7
c1 c2
d1 d2 d3 d4 d5

Combines into (brackets are just to highlight steps, so they really mean nothing):
(a1 b1 c1 d1) (a2 b2 c2 d2) (a3 b3 d3) (a4 b4 d4) (b5 d5) (b6) (b7)

Also, I'd like to combine variable number of array, not just 3 or 4

like image 688
Fluffy Avatar asked Apr 21 '10 10:04

Fluffy


2 Answers

String result[] = new String[a.length+b.length+c.length];
for (int i = 0, j = 0; j < result.length; ++i) {
    if (i < a.length) {
        result[j++] = a[i];
    }
    if (i < b.length) {
        result[j++] = b[i];
    }
    if (i < c.length) {
        result[j++] = c[i];
    }
}

UPDATE: more generally

String[] merge(String[]... arrays) {
    int length = 0;
    for (String[] a: arrays) {
        length += a.length;
    }
    String result[] = new String[length];
    for (int i = 0, j = 0; j < length; ++i) {
        for (String[] a: arrays) {
            if (i < a.length) {
                result[j++] = a[i];
            }
        }
    }
    return result;
}
like image 110
Maurice Perry Avatar answered Nov 04 '22 10:11

Maurice Perry


String[] answer = new String[a.length + b.length + c.length];
int maxLength = Math.max(a.length, Math.max(b.length, c.length));

int counter = 0;    
for (int i = 0; i < maxLength; i++)
{
   if (i < a.length)
      answer[counter++] = a[i];

   if (i < b.length)
      answer[counter++] = b[i];

   if (i < c.length)
      answer[counter++] = c[i];
}
like image 31
Petar Minchev Avatar answered Nov 04 '22 08:11

Petar Minchev