Skip to content

Instantly share code, notes, and snippets.

@yewton
Created May 18, 2012 05:23
Show Gist options
  • Save yewton/2723321 to your computer and use it in GitHub Desktop.
Save yewton/2723321 to your computer and use it in GitHub Desktop.
LCG, xor shift
#include <iostream>
using namespace std;
class LCG {
unsigned long s;
static const unsigned long M = 1103515245UL;
static const unsigned long A = 12345UL;
static const unsigned long B = 2147483647UL;
public:
LCG() : s(0) {}
LCG(unsigned long seed) : s(seed) {}
unsigned long get();
unsigned long get(int min, int max);
};
unsigned long LCG::get() {
s = (A * s + B) % M;
return s;
}
unsigned long LCG::get(int min, int max) {
return (get() + min) % max;
}
class XORShift {
unsigned long x;
unsigned long y;
unsigned long z;
unsigned long w;
public:
XORShift() : x(123456789),
y(362436069),
z(521288629),
w(88675123) {}
XORShift(unsigned long x,
unsigned long y,
unsigned long z,
unsigned long w) : x(x), y(y), z(z), w(w) {}
unsigned long get();
unsigned long get(int min, int max);
};
unsigned long XORShift::get() {
unsigned long t = (x^(x<<11));
x = y; y = z; z = w;
return w = (w^(w>>19))^(t^(t >> 8));
}
unsigned long XORShift::get(int min, int max) {
return (get() + min) % max;
}
int main() {
unsigned long seed = 0;
cout << "input seed: ";
cin >> seed;
LCG l(seed);
XORShift xors;
for (int i = 0; i < 10; i++) {
cout << l.get(0, 100) << endl;
}
cout << "------" << endl;
for (int i = 0; i < 10; i++) {
cout << xors.get(0, 100) << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment