簡體   English   中英

如何從數組列表中獲取多個隨機元素?

[英]how to get multiple random elements from an array list?

標題基本上描述了我的問題......我想從數組列表中獲取 3 個元素而不會重復。 因為我發現的其他人使用Math.floor((Math.random() * list.length))我認為它只限於一個輸出。

一個集合中的 n 個唯一元素是一個組合

無需了解太多細節, combinations = variations * permutations ,這意味着我們可以只生成一個變體(長度相同)而忽略順序。

例如, Fisher-Yates shuffle可以做到這一點:

function shuffled(elements){
    // Return shuffled elements such that each variation has the same probability
    const copy = [...elements];
    for(let i = copy.length - 1; i >= 0; i--){
        let j = Math.floor(Math.random() * (i + 1)); // 0 <= j <= i
        let tmp = copy[i];
        copy[i] = copy[j];
        copy[j] = tmp;
    }
    return copy;
}
function choose(elements, n){
    // Return a combination of n elements
    return shuffled(elements).slice(0, n);
}

var elements = ['a', 'b', 'c', 'd'];

var N = 1000;
var results = {}; // how many times each element was chosen
for(let i = 0; i < N; i++){
    for(let x of choose(elements, 3)){
        results[x] = (results[x] || 0) + 1;
    }
}

console.log(results); // 3/4 * N = 750

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM