4/08/2011

Random

Here are some useful snippets for random.

Math.random() returns a pseudo-random number n, where 0 <= n < 1. It's good enough for all our random needs in Flash.


Random integer from 0 to n-1 int(Math.random()*n);
Random color int(Math.random()*0xFFFFFF);
Function that returns a random integer n in a range, where min <= n < max. function randomBtw(min:int,max:int):int{ return int(Math.random()*(max-min))+min; }
Getting a random item from an array arr[int(Math.random()*arr.length)]
Randomizes an array (this is faster than splice or sort methods) function randomizeArray(arr:Array):void{ var l:int=arr.length; var t:Object; var r:int; for(var i:int=0;i<l;i++){ r=int(Math.random()*l); if(r!=i){ t=arr[i]; arr[i]=arr[r]; arr[r]=t; } } }
Function that has a percent chance of returning true. percent should be between 0-1 function chance(percent:Number):Boolean{ return (Math.random()<=percent); }

No comments:

Post a Comment