This post has nothing to do with flash, but it is just an algorithm, which generates any number of distinct random integers from a given range. I thought of it, at the time I was to apply it to one of the applications I was working on. And it really worked.
public function getDistinctRandomNumbers(range, numCount):Array
{
// NumCount is the count of random numbers to be generated
// Range is the upper limit of the generated random numbers, starting from 0.
var newArray = new Array();
var randNum2:int;
var randNum1 = Math.floor(Math.random() * range);
newArray.push(randNum1);
for(var k:int = 0; k < numCount - 1; k++)
{
randNum2 = Math.floor(Math.random() * range);
var len = newArray.length;
var count:int = 0;
while(count < len)
{
while(randNum2 == newArray[count])
{
randNum2 = Math.floor(Math.random()*range);
count = 0;
}
count++;
}
newArray.push(randNum2);
}
return newArray;
}
This algorithm has a worst case complexity of O(n^3), hence it cannot be considered an optimized solution. Will get back with a better solution.
No comments:
Post a Comment