PS: I mentioned that a random sort was not the best approach.
Here's a better way to randomize an array: public static function shuffle(array:Array):void { var tmp:*; var cur:int; var top:int; cur = top = array.length; if(top) { while(--top) { cur = Math.floor(Math.random() * (top + 1)); tmp = array[cur]; array[cur] = array[top]; array[top] = tmp; } } } 2011/1/13 Juan Pablo Califano <califa010.flashcod...@gmail.com> > Try this: > > function uniqueRandomInt(min:Number, max:Number, n:Number) { > var a:Array = []; > var i:Number = min; > while (a.push(i++)<max); > a.sort(function (a:Number, b:Number) { > return Math.floor(Math.random()*3)-1; > > }); > return a.slice(0,n); > } > > Although a random sort is not the best means to randomize an array, it > should work reasonably. > > The problem with your code was this line: > > Math.random()*2-1; > > Your sort function should return 3 diferent values (n < 1, n = 0 and; n > > 0) as evenly distributed as possible. Math.random gives you a number that > is great or equal to 0 and *less* than 1. It will not give you 1 back > (0.999999999, but not 1). > > So if you do: > > Math.random() * 2 > > You'll either get 0 or 1 (with decimals); it's not posibble to get 2. You > should instead use 3 as the multiplier and floor it; the result should be 0, > 1 or 2 (this will have as much randomness as Math.random provides). Now > substract 1 and you'll get -1, 0 or 1, which is what you want for your sort > function. > > > Cheers > Juan Pablo Califano > 2011/1/13 natalia Vikhtinskaya <natavi.m...@gmail.com> > > Hi >> I use function that creates unique array >> >> function uniqueRandomInt(min:Number, max:Number, n:Number) { >> var a:Array = []; >> var i:Number = min; >> while (a.push(i++)<max) { >> ; >> } >> a.sort(function (a:Number, b:Number) { return >> Math.random()*2-1;}); >> return a.slice(0, n); >> } >> >> It works fine for AS2. But for AS3 it gives always the same result >> if I ask >> uniqueRandomInt(1, 6, 6); I always get 4,2,3,1,5,6 >> >> What is wrong in this code for AS3? >> >> Thank you in andvance. >> _______________________________________________ >> Flashcoders mailing list >> Flashcoders@chattyfig.figleaf.com >> http://chattyfig.figleaf.com/mailman/listinfo/flashcoders >> > > _______________________________________________ Flashcoders mailing list Flashcoders@chattyfig.figleaf.com http://chattyfig.figleaf.com/mailman/listinfo/flashcoders