簡體   English   中英

將第二個數組的元素隨機分布在第一個數組中

[英]distribute the elements of second array inside the first array randomly

假設我們有一個這樣的數組:

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

而我們要在上面的數組中隨機分布另一個數組的元素:

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

因此,例如,我們有這樣的結果:

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

請注意,arrays 的順序保持不變,但第二個數組隨機分布在第一個數組內。

您可以收集給定數組的所有索引,例如此處的0代表a1代表b ,對數組進行洗牌並按順序獲取值。

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

我猜你可以循環遍歷數組“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