首页 > 解决方案 > 如何从数组列表中获取多个随机元素?

问题描述

标题基本上描述了我的问题......我想从数组列表中获取 3 个元素而不会重复。因为我发现的其他人使用Math.floor((Math.random() * list.length))认为仅限于一个输出。

标签: javascriptdiscord.js

解决方案


一组中的 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

推荐阅读