randRange with propability for even/odd

by pleclech forked from flash on 2011-2-25 (diff: 18)
♥0 | Line 40 | Modified 2011-05-08 04:29:24 | MIT License
play

ActionScript3 source code

/**
 * Copyright pleclech ( http://wonderfl.net/user/pleclech )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/9IHx
 */

// forked from pleclech's flash on 2011-2-25
package {
    import flash.display.Sprite;
    public class FlashTest extends Sprite {
        public function FlashTest() {
             if (stage) _init()
            else addEventListener(Event.ADDED_TO_STAGE, _init)
        }
        import flash.text.TextField;
        import flash.events.Event;

        private var tf:TextField=new TextField()
        private function trace(...args):void{
            tf.appendText(args.join(", ")+"\n")
        }
        private function _init(e:Event=null):void {
            removeEventListener(Event.ADDED_TO_STAGE, _init)
            addChild(tf)
            tf.autoSize="left"
            tf.background=true
            start()
       }
       public function randomRange(low:int, high:int, evenProbability:Number = 0.5):int{
           var ret:int = int( Math.random() * ( 1 + high - low ) ) + low
           return ( ret & -2 ) | int( Math.random() >= evenProbability )
       }
       private function test(loop:int, prob:Number):void {
           var oddCount:int=0
           
           for (var i:int=0;i<loop;++i) {
                var ret:int=randomRange(1, 20, prob) 
                oddCount += (ret & 1)
           }
           trace("prob of even: "+prob+", even : "+(loop-oddCount), "odd : "+oddCount)           
       }

       private function start():void {
           const loop:int=100000
           test(loop, 0.5)
           test(loop, 0.7)
           test(loop, 0.2)
       }
    }
}