Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How to randomly sample items without replacement?

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.

like image 239
seRgiOOOOOO Avatar asked Oct 20 '12 10:10

seRgiOOOOOO


2 Answers

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());
like image 200
Strille Avatar answered Oct 19 '22 17:10

Strille


using d3:

var bucket = d3.shuffle(d3.range(11));

while(bucket.length) {
  console.log(bucket.pop());
}
like image 44
keithpjolley Avatar answered Oct 19 '22 18:10

keithpjolley