Skip to content

Instantly share code, notes, and snippets.

@ashfn
Created June 20, 2025 19:38
Show Gist options
  • Save ashfn/72a240452de5abe220ede20ffc52d38e to your computer and use it in GitHub Desktop.
Save ashfn/72a240452de5abe220ede20ffc52d38e to your computer and use it in GitHub Desktop.
#include <iostream>
#include <fstream>
#include <array>
#include <random>
// more specifically this will be mt19937
// constant f value used for 32 but mt19937
#define f 1812433253
std::array<uint32_t,624> mt19937_init(uint32_t seed){
std::array<uint32_t,624> state;
state[0] = seed;
for(int i=1; i<624; i++){
state[i]= f*(state[i-1] ^ (state[i-1] >> 30)) + i;
}
return state;
}
std::array<uint32_t,624> mt19937_twist(std::array<uint32_t,624> state){
std::array<uint32_t,624> newstate;
for(int i=0; i<624; i++){
uint32_t oldstate = state[i];
// concating the MSB and LSB from next
uint32_t x;
if(i+1<624){
x = (state[i] & 0x80000000) | (state[(i+1)] & 0x7FFFFFFF);
}else{
x = (state[i] & 0x80000000) | (newstate[(i+1)%624] & 0x7FFFFFFF);
}
// does the *A part
if(x&1){
x = (x>>1) ^ 0x9908B0DFUL;
}else{
x=x>>1;
}
uint32_t y;
if(i+397<624){
y = state[i+397] ^ x;
}else{
y = newstate[(i+397) % 624] ^ x;
}
newstate[i] = y;
}
return newstate;
}
std::array<uint32_t,624> mt19937_temper(std::array<uint32_t,624> state){
std::array<uint32_t, 624> tempered;
for(int i=0; i<624; i++){
uint32_t y = state[i];
y = y ^ (y >> 11);
y = y ^ ((y << 7) & 0x9D2C5680UL);
y = y ^ ((y << 15) & 0xEFC60000UL);
tempered[i] = y ^ (y >> 18);
}
return tempered;
}
class mt19937_generator {
public:
uint32_t seed;
uint32_t generate() {
uint32_t generated = random_values[position];
position++;
if(position>=624){
nextblock();
}
return generated;
}
mt19937_generator(uint32_t genSeed){
seed = genSeed;
state = mt19937_init(seed);
nextblock();
}
private:
std::array<uint32_t,624> state;
std::array<uint32_t,624> random_values;
int position;
// goes to next block of 624 values
void nextblock() {
state = mt19937_twist(state);
random_values = mt19937_temper(state);
position = 0;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment