Skip to the content of the web site.

Project W.5: Interleave

This function takes two arrays and creates a dynamically allocated array of the appropriate capacity alternately copying entries from the two arrays into the new array.

    int array_1[4]{ 1,  2,  3,  4};
    int array_2[4]{10, 20, 30, 40};

    int *array_3{ interleave( array_1, 4, array_2, 4 );
        // array_3 has capacity 8 with entries {1, 10, 2, 20, 3, 30, 4, 40}

If the capacity of the first array is greater than the capacity of the second, the capacity of the new array will be 2*capacity_1 - 1 and capacity_1 - capacity_2 - 1 entries will be set to 0. If the capacity of the second array is greater than the capacity of the first, the capacity of the new array will be 2*capacity_2 and capacity_2 - capacity_1 entries will be set to 0.

Integer implementation

int *interleave( int array_1[], std::size_t capacity_1,
                 int array_2[], std::size_t capacity_2 );

Templated implementation

For templated implementations, you could use 0 as the default value, but it is better to use the default value of the templated type: T{}.

template <typename T>
T *interleave( T array_1[], std::size_t capacity_1,
               T array_2[], std::size_t capacity_2 );