// Twister.cpp #include "stdafx.h" #include "Twister.h" // Mersenne Twister MT19937 with some subtle changes. const int Twister::StateCount=624; DWORD Twister::State[StateCount]; // Initially seeded using GetTickCount(); int Twister::Index=Seed(); // Index to the State array. int Twister::Seed(DWORD Seed/*=GetTickCount()*/) { DWORD* it=State; *it=Seed; for(int i=StateCount-1; i; --i) { DWORD Previous=*it++; *it=(1812433253*(Previous^(Previous>>30))+i); } return StateCount; // Only for the initialisation of Index, to get FillStates() get called during the next Get(). } DWORD Twister::Get() { // The fundamental method (quickest return) if(Index>=StateCount) FillStates(); DWORD d=State[Index++]; d^=(d>>11); // Mersenne Twister MT19937 Coefficients: d^=(d<< 7) & 0x9D2C5680; d^=(d<<15) & 0xEFC60000; d^=(d>>18); return d; } void Twister::FillStates() { const int M=397; for(int i=StateCount-M; i--;) SetState(i, i+1, i+M); for(int i=StateCount-1; i--;) SetState(i, i+1, i+(M-StateCount)); SetState(StateCount-1, 0, M-1); Index=0; } void Twister::SetState(int i, int j, int k) { DWORD y=(State[i] & 0x80000000) | (State[j] & 0x7FFFFFFF); State[i]=State[k]^(y>>1)^((y&1)*0x9908B0DF); }