Merging Arrays

Difficulty: ★ ★ ☆ ☆

You have a number of options for merging values between two arrays. I suppose the solution you devise depends on how you interpret the word “merge.”

For example, you could just stick one array onto the end of another:

Array 'a': 22 41 92 67 16
Array 'b': 34 16 57 46 22
'a' + 'b': 22 41 92 67 16 34 16 57 46 22

You could create a single array and eliminate any overlap between the two, snipping out the duplicate values:

Array 'a': 22 41 92 67 16
Array 'b': 34 16 57 46 22
'a' + 'b': 22 41 92 67 16 34 57 46

Above, the values 22 and 16 appear only once in the result.

You can also sort the arrays to present the concatenated result sequentially. But for this month’s Exercise, I’d like you to zipper the arrays together. This color-coded sample output saving me many words of text:

Array 'a': 22 41 92 67 16
Array 'b': 34 16 57 46 22
'a' + 'b': 22 34 41 16 92 57 67 46 16 22

I call it a “zipper” because the values from each original array alternate in the result, as shown above.

Your task for this month’s challenge is to write a merge() function that swallows two arrays of equal size. It returns a new array that contains values from the two original arrays, but zippered together. (You don’t have to code color output.)

Here is a skeleton to help get you started:

2023_03_01-Lesson.c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 5

/* merge function goes here */

int main()
{
    int x,a[SIZE],b[SIZE],*c;

    /* seed the randomizer */
    srand( (unsigned)time(NULL) );

    /* populate the arrays, values 0 through 99 */
    for( x=0; x<SIZE; x++ )
    {
        a[x] = rand()%100;
        b[x] = rand()%100;
    }

    /* output the arrays */
    printf("Array 'a': ");
    for( x=0; x<SIZE; x++ )
        printf(" %2d",a[x]);
    putchar('\n');
    printf("Array 'b': ");
    for( x=0; x<SIZE; x++ )
        printf(" %2d",b[x]);
    putchar('\n');

    /* call the merge() function */
    /* output the merged arrays */

    return(0);
}

Your merge() function sits where the comment is at Line 7 in the code. After the two original arrays a[] and b[] are stuffed with random values and output, the merge() function is called. Then, in the main() function, output the merged arrays, as shown earlier.

Please try this Exercise on your own before you peek at my solution.

Leave a Reply