Friday, April 1, 2011

Lottery Number Function

Again following from a previous discussions on generating unique random numbers within a range, here's a quick function you can use when the range starts from 1, just as most lottery draws do.

var getRandomLottoNumbers = function (m:Number, n:Number):Array {
for(var v=[];m;--n)Math.random()*n>m?0:v[--m]=n;return v

Using it is quite straightforward. Just pass two arguments to the function - the number of selections you want to make (m), and the total numbers you are selecting from (n). If you omit the arguments, the function will default to selecting 6 random numbers from a total of 49:

// generate 3 random numbers between 1 and 10
trace(getRandomLottoNumbers(3, 10));
// generate 6 random numbers between 1 and 49 (default)