javascript - 如何从数组列表中获取多个随机元素?
问题描述
标题基本上描述了我的问题......我想从数组列表中获取 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
推荐阅读
- angular - 来自多个孩子的输出和发射器
- android - 我添加了隐私政策来玩商店和我的应用程序。我的应用程序已经 10 个小时没有再次发布
- asp.net-mvc - .Net Core MVC 2.1 中是否有等效的会话开始?
- sql - 使用“BEGIN TRANSACTION”和“END TRANSACTION”来提高性能
- javafx - 带有 JavaFx 11 和 JDK 11 的 Netbeans 9.0
- android - 如何在android的firebase数据库中仅获取最近添加的消息
- python - Python在不使用函数的情况下获取当前类名
- websphere - swagger.json 端点在 WAS 服务器上抛出“404 Not Found”
- php - 使用php提取所有'img'标签所在的'a'标签,但我无法弄清楚
- python - 如何通过显式设置其值来替换字节类型的python对象中的单个位