JavaScript-如何随机抽样而不替换? [英] JavaScript - How to randomly sample items without replacement?

查看:278
本文介绍了JavaScript-如何随机抽样而不替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript

我尝试搜索类似的内容,但找不到.

这是一个简单的主意:

a.取一个介于0到10之间的随机数.

b.假设滚动的随机数是3.

c.然后,保存数字(3).

d.现在,再取一个介于0到10之间的另一个随机数,但是它不可能是3,因为它已经出现了.

解决方案

一种解决方案是生成一个数组(一个存储桶"),该数组包含您要选择的所有值,在这种情况下为0到10之间的所有数字.您从阵列中随机选择一个,并将其从存储桶中删除.请注意,下面的示例不会检查存储桶是否为空,因此,如果您在下面调用该函数超过10次,则会收到错误消息.

var bucket = [];

for (var i=0;i<=10;i++) {
    bucket.push(i);
}

function getRandomFromBucket() {
   var randomIndex = Math.floor(Math.random()*bucket.length);
   return bucket.splice(randomIndex, 1)[0];
}

// will pick a random number between 0 and 10, and can be called 10 times
console.log(getRandomFromBucket());

JavaScript

I've tried searching for something like this, but I am not able to find it.

It's a simple idea:

a. Take a random number between 0 to 10.

b. Let's say the random number rolled is a 3.

c. Then, save the number (the 3).

d. Now, take another random number again between 0 to 10, but it can't be the 3, because it has already appeared.

解决方案

One solution is to generate an array (a "bucket") with all the values you want to pick, in this case all numbers from 0 to 10. Then you pick one randomly from the array and remove it from the bucket. Note that the example below doesn't check if the bucket is empty, so if you call the function below more than 10 times you will get an error.

var bucket = [];

for (var i=0;i<=10;i++) {
    bucket.push(i);
}

function getRandomFromBucket() {
   var randomIndex = Math.floor(Math.random()*bucket.length);
   return bucket.splice(randomIndex, 1)[0];
}

// will pick a random number between 0 and 10, and can be called 10 times
console.log(getRandomFromBucket());

这篇关于JavaScript-如何随机抽样而不替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆