-3

Let's say we have an array like this:

const a = [1,2,3,4,5,6,7]

And we want to randomly distribute the elements of another array in the above array:

const b = ['a', 'b', 'c', 'd', 'e']

So that for instance we have the result like this:

[1, 'a', 'b', 2, 3, 4, 'c', 5, 6 'd', 'e', 7, 8]

Note that the order of both arrays remain intact but the second array distributed randomly inside the first array.

Sara Ree
  • 3,417
  • 12
  • 48
  • 1
    [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions), [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas May 18 '21 at 14:05
  • Please explain us the logic of the order you want in your new array. it's will help us understand your question – Eitan Rosati May 18 '21 at 14:06
  • How about you generate a random number that varies from `0` to the `length-1` of the first array (so here 0 to 6), and insert the elements of the second array using a for loop into the randomly generated position. – c_anirudh May 18 '21 at 14:07

2 Answers2

1

You could collect all indices of the given array, like here 0 for a and 1 for b, shuffle the array and take the values in order.

Fisher-Yates shuffling algorithm taken from here: https://stackoverflow.com/a/2450976/1447675.

const
    random = (...args) => {
        let array = args.reduce((r, [...a], i) => [...r, ...a.fill(i)], []),
            currentIndex = array.length,
            temporaryValue,
            randomIndex,
            indices = args.map(_ => 0);

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {
            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array.map(i => args[i][indices[i]++]);
    }
    a = [1, 2, 3, 4, 5, 6, 7],
    b = ['a', 'b', 'c', 'd', 'e'],
    result = random(a, b);

console.log(...result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Amazing Job... Thank you very much.... I tried not to pick up your solution this time but it works like nothing else :) – Sara Ree May 18 '21 at 15:56
1

I guess you could loop through array "b", use the .length of array "a" (which gets updated each splice) and splice values of "b" into "a" at random index of "a".

const shuffle = (function() {

    const a = [1,2,3,4,5,6,7];
    const b = ['a', 'b', 'c', 'd', 'e'];

    // Initial "starting" index.
    const initialRndInt = getRandomInt(0, a.length);
    
    b.forEach((value, index) => {

        // Int used in the actual splicing.
        const followingRndInt = function() {

            // Just return initial int.
            if(index === 0) {

                return initialRndInt;
            }

            // kinda bad way to look where the previous value was placed, maybe just add extra variable to keep track of the index.
            return getRandomInt(a.indexOf(b[index - 1]) + 1, a.length);
        }();

        // Shove it in there.
        a.splice(followingRndInt, 0, value);
    });

    // Function from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
    function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
    }

    console.log(a);
})();