开发者

javascript: generate 2 random but distinct numbers from range

quick question:

What is the 开发者_Go百科best way for implementing this line of python code (generates two random but distinct numbers from a given range)...

random.sample(xrange(10), 2)

...in Javascript?

Thanks in advance!

Martin


Here is my attempt using splice:

var a = [1,2,3,4,5,6,7,8,9,10];var sample = [];
sample.push(a.splice(Math.random()*a.length,1));
sample.push(a.splice(Math.random()*a.length,1));

Wrapped in a function:

function sample_range(range, n) {
  var sample = [];
  for(var i=0; i<n; i++) {
    sample.push(range.splice(Math.random()*range.length,1));
  }

  return sample;
}

var sample = sample_range([1,2,3,4,5,6,7,8,9,10], 2);

We could also stick the function into Array.prototype to have something like dot notation syntax:

Array.prototype.sample_range = function(n) {
    var sample = [];
    for(var i=0;i<n;i++) {
      sample.push(this.splice(Math.random()*this.length,1));
    }
    return sample;
};
var sample = [1,2,3,4,5,6,7,8,9,10].sample_range(2);


If you want to generate random numbers between 0 and n, one way is to randomly pick number r1 in 0..n then pick r2 from 0..n-1 and add 1 to r2 if r2 >= r1.


function sample(range,tot){
    if(tot > range){
        alert('infinite loop?');
        return [];
    }
    var myRandomNumbers = [];
    for(var i = 0; i<tot; i++){
        var randN = Math.floor(Math.random()*range);
        while(myRandomNumbers.contains(randN)){
            randN = Math.floor(Math.random()*range);
        }
        myRandomNumbers.push(randN);
    }
    return myRandomNumbers
}

var nums = sample(10,2); //array containing 2 distinct random numbers


Generate one, then repeatedly generate the second until it's not the same as the first. Tiny chance it will have to run longer, but you won't see any performance hit unless you need to generate billions of numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜