简体   繁体   中英

distribute the elements of second array inside the first array randomly

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.

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);

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); })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM