Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing two arrays by alternating elements (zipper style)

Tags:

algorithm

What is an elegant algorithm to mix the elements in two arrays (of potentially differing sizes) so that the items are drawn in an alternating fashion from each array, with the leftovers added to the end?

E.g.

Array 1 - A, B, C, D, E, F, G

Array 2 - 1, 2, 3, 4

Mixed array - A, 1, B, 2, C, 3, D, 4, E, F, G

I would prefer the solution in C#, but I should be able to read and transpose solutions in any language (or even some form of pseudo code).

Don't worry about null checking or any other edge cases, I'll handle those.

like image 903
Brian Hinchey Avatar asked Mar 26 '09 03:03

Brian Hinchey


People also ask

Is the process of combining the elements of two arrays?

QUESTION 14The process of combining/merging of the two sorted arrays into the third array in sorted form (without. sorting) without any duplicate element is known as merge sort.

How do I print two arrays together?

You can try printing the second array with a second statement or concatenating the string representations of the two arrays and printing that string in a single statement. The following may be useful in getting the string representation of the arrays: Arrays. toString(array) . Show activity on this post.


1 Answers

You mean something along the lines of this?

// naive/boring approach
int i = 0;
int m = 0;
while (i < a1.size() || i < a2.size()) {
    if (i < a1.size())
        mixed[m++] = a1[i];
    if (i < a2.size())
        mixed[m++] = a2[i];
    i++;
}

If you use this, you'll probably want to store the array lengths in variables so you don't have to keep calling a size() method (or whatever it is in whatever language you use).

like image 108
Ryan Graham Avatar answered Oct 19 '22 22:10

Ryan Graham