简体   繁体   English

将第二个数组的元素随机分布在第一个数组中

[英]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.请注意,arrays 的顺序保持不变,但第二个数组随机分布在第一个数组内。

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.您可以收集给定数组的所有索引,例如此处的0代表a1代表b ,对数组进行洗牌并按顺序获取值。

Fisher-Yates shuffling algorithm taken from here: https://stackoverflow.com/a/2450976/1447675 . Fisher-Yates 改组算法取自此处: 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".我猜你可以循环遍历数组“b”,使用数组“a”的.length(每个拼接都会更新)并将“b”的值拼接到“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); })();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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