ChickenStealer
ChickenStealer

Reputation: 21

How do you combine two arrays in such a way that the two are equally distributed?

It is way easier to give an example than to explain it with words. Starting with 2 arrays:

{a,a,a,a,a,a,a} and {b,b,b}

I would like the output to be:

{a,a,b,a,a,b,a,a,b,a}

With a little help I found the following:

    let result = [];
    let ratio = array1.length / array2.length;
    let pushA = 0;
    while (array2.length >0) {
        pushA+= ratio;
        while (pushA >= 1){
            result.push(array1.pop());
            pushA--;
        }
        result.push(array2.pop());

    }

    return result;

Upvotes: 2

Views: 89

Answers (2)

BishalG
BishalG

Reputation: 1434

For simple application, you may find size of both arrays. For example suppose size of fist array is M and size of second array is N. Also suppose M>=N ( If not you may interchange both arrays ).

Now, you may easily find total elements of First array to be inserted before inserting one element from Second array , which is equal to: M/N ( = K,say ).

So, while merging, you may insert K elements from First array then one element from Second array and so on untill elements exists in both arrays.

Upvotes: 0

MBo
MBo

Reputation: 80232

Slightly non-traditional way:

Use simplest implementation of Bresenham algorithm for segment with coordinates (0,0) - (A.Length, B.Length)

When x is incremented - insert "a", when y - insert "b" (in general case - use next index from corresponding array)

Upvotes: 1

Related Questions