javascript: generate 2 random but distinct numbers from range -
quick question:
what best way implementing line of python code (generates 2 random distinct numbers given range)...
random.sample(xrange(10), 2)
...in javascript?
thanks in advance!
martin
here attempt using splice:
var = [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 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 stick function array.prototype have 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);
Comments
Post a Comment