Created
July 27, 2019 02:14
-
-
Save evan-moon/c7a8957beedc9b0e87783f2a548a5e42 to your computer and use it in GitHub Desktop.
메르센 트위스터 난수 생성 알고리즘
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const N = 624; | |
const M = 397; | |
const F = 1812433253; | |
const UPPER_MASK = (2 ** 32) / 2; // 0x80000000 | |
const LOWER_MASK = UPPER_MASK - 1; // 0x7fffffff | |
const MATRIX_A = 0x9908b0df; | |
class MersenneTwister { | |
constructor () { | |
const initSeed = new Date().getTime(); | |
this.mt = new Array(N); | |
this.index = N + 1; | |
this.seedMt(initSeed); | |
} | |
seedMt (seed) { | |
let s; | |
this.mt[0] = seed >>> 0; | |
for (this.index = 1; this.index < N; this.index++) { | |
this.mt[this.index] = F * (this.mt[this.index - 1] ^ (this.mt[this.index - 1]) >>> 30) + this.index; | |
this.mt[this.index] &= 0xffffffff; | |
} | |
} | |
int () { | |
let y; | |
const mag01 = new Array(0, MATRIX_A); | |
if (this.index >= N) { | |
let kk; | |
if (this.index === N + 1) { | |
this.seedMt(5489); | |
} | |
for (kk = 0; kk < N - M; kk++) { | |
y = (this.mt[kk] & UPPER_MASK) | (this.mt[kk + 1] & LOWER_MASK); | |
this.mt[kk] = this.mt[kk + M] ^ (y >>> 1) ^ mag01[y & 1]; | |
} | |
for (; kk < N - 1; kk++) { | |
y = (this.mt[kk] & UPPER_MASK) | (this.mt[kk + 1] & LOWER_MASK); | |
this.mt[kk] = this.mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 1]; | |
} | |
y = (this.mt[N - 1] & UPPER_MASK) | (this.mt[0] & LOWER_MASK); | |
this.mt[N - 1] = this.mt[M - 1] ^ (y >>> 1) ^ mag01[y & 1]; | |
this.index = 0; | |
} | |
y = this.mt[this.index++]; | |
y ^= (y >>> 11); | |
y ^= (y << 7) & 0x9d2c5680; | |
y ^= (y << 15) & 0xefc60000; | |
y ^= (y >>> 18); | |
return y >>> 0; | |
}; | |
} | |
const m = new MersenneTwister(); | |
console.log(m.int()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment