Mersenne Twister
MersenneTwister
http://www.devslash.com/?p=97
@author paq
/**
* Copyright paq ( http://wonderfl.net/user/paq )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/m22B
*/
package
{
import com.bit101.components.InputText;
import com.bit101.components.Label;
import com.bit101.components.PushButton;
import com.bit101.components.Text;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* MersenneTwister
* http://www.devslash.com/?p=97
* @author paq
*/
[SWF(width=465, height=465, backgroundColor=0xFFFFFF, frameRate=24)]
public class Mersenne extends Sprite
{
public function Mersenne():void
{
__init();
}
private var _input:InputText;
private var _result:Text;
private function __init():void
{
new Label(this, 12, 13, "seed:");
new PushButton(this, 150, 12, "generate", __seedButton_push__);
_input = new InputText(this, 42, 12, "1");
_input.restrict = "0123456789";
_input.height = 20;
_result = new Text(this, 12, 48);
_result.setSize(441, 405);
_result.editable = false;
}
private function __seedButton_push__($event:MouseEvent):void
{
MersenneTwister.initialiseGenerator(int(_input.text));
_result.text = MersenneTwister.generateRandomNum() + "\n" + _result.text;
}
}
}
class MersenneTwister
{
private static var MT:Array = new Array();
private static var y:Number, z:Number = 0;
public static function initialiseGenerator(seed:Number):void
{
MT[0] = seed;
for(var i:int=1; i<623; i++)
MT[i] = ((0x10dcd * MT[i-1]) + 1)& 0xFFFFFFFF
}
private static function generateNumbers():void
{
z = 0;
for(var i:int=0; i<623; i++)
{
y = 0x80000000 & MT[i] + 0x7FFFFFFF & (MT[(i+1)%624]);
if((y % 2) == 0)
MT[i] = MT[(i + 397) % 624] ^ (y >> 1);
else
MT[i] = MT[(i + 397) % 624] ^ (y >> 1) ^ 0x9908B0DF;
}
}
public static function extractNumber(i:Number):Number
{
y = MT[i];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= (y >> 18);
return y;
}
public static function generateRandomNum():Number
{
if(z >= 623)
generateNumbers();
return extractNumber(z++);
}
}