Q:

javascript: generate 2 random but distinct numbers from range

quick question:
What is the 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

A:

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);

A:

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.

