PU2213/src/js/mersennetwister.js

70 lines
1.7 KiB
JavaScript

// Code adapted to JS module. Original mersenne.js (c) 2014 Stephan Brumme.
export class MersenneTwister {
constructor( seed ) {
this.state = new Array(624);
this.next = null;
if ( seed === undefined ) {
seed = 5489;
}
this.seed = seed;
this.state[ 0 ] = this.seed;
let s = null;
for ( let i = 1 ; i < 624; i++ ) {
s = this.state[ i - 1 ] ^ ( this.state[ i - 1 ] >>> 30);
this.state[ i ] = ( ( ( ( ( s & 0xffff0000 ) >>> 16 ) * 1812433253 ) << 16 ) +
( s & 0x0000ffff ) * 1812433253 ) + i;
this.state[ i ] |= 0;
}
this.twist();
}
twist() {
let i = 0;
let bits = 0;
for ( i = 0; i < 227; i++ )
{
bits = ( this.state[ i ] & 0x80000000) | ( this.state[ i + 1 ] & 0x7fffffff);
this.state[ i ] = this.state[ i + 397 ] ^ ( bits >>> 1 ) ^ ( ( bits & 1 ) * 0x9908b0df );
}
for ( i = 227 ; i < 623; i++ )
{
bits = ( this.state[ i ] & 0x80000000) | ( this.state[ i + 1 ] & 0x7fffffff );
this.state[ i ] = this.state[ i - 227 ] ^ ( bits >>> 1 ) ^ ( ( bits & 1 ) * 0x9908b0df );
}
bits = ( this.state[ 623 ] & 0x80000000 ) | ( this.state[ 0 ] & 0x7fffffff );
this.state[ 623 ] = this.state[ 396 ] ^ ( bits >>> 1 ) ^ ( ( bits & 1 ) * 0x9908b0df );
this.next = 0;
}
random = function() {
if ( this.next >= 624 ) {
this.twist();
}
let x = this.state[ this.next++ ];
x ^= x >>> 11;
x ^= (x << 7) & 0x9d2c5680;
x ^= (x << 15) & 0xefc60000;
x ^= x >>> 18;
return x;
}
randomRange( min, max ) {
let x = Math.abs( this.random() );
let l = Math.pow( 10, x.toString().length );
let y = Math.round( ( Math.floor( ( x / l ) * ( Math.floor( max * 100 ) - Math.ceil( min * 10 ) ) ) + Math.ceil( min * 10 ) ) / 100 );
return y;
}
}