00001 #ifndef RANDGEN_HPP_
00002 #define RANDGEN_HPP_
00003
00004 #include <math.h>
00005
00006 #include<vector>
00007
00008
00009 unsigned int randgen_sys_rand()
00010 {
00011 return rand();
00012 }
00013
00014 class RandGen
00015 {
00016 private:
00017 double nextG;
00018 bool hasNextG;
00019
00020 protected:
00021 long seed;
00022 bool init;
00023
00024 public:
00025 RandGen()
00026 {
00027 seed = time(NULL);
00028 init = false;
00029 }
00030
00031 RandGen(long _seed) :
00032 seed(_seed)
00033 {
00034 if (seed < 0)
00035 seed *= (-1);
00036 init = false;
00037 }
00038
00039 virtual ~RandGen()
00040 {
00041 }
00042
00043
00044 virtual void initialize()
00045 {
00046 srand(seed);
00047 hasNextG = false;
00048 }
00049
00050
00051 virtual int rand()
00052 {
00053 if (!init)
00054 {
00055 initialize();
00056 init = true;
00057 }
00058
00059 return (int) randgen_sys_rand();
00060 }
00061
00062
00063 virtual int rand(int n)
00064 {
00065 if (!init)
00066 {
00067 initialize();
00068 init = true;
00069 }
00070
00071 return randgen_sys_rand() % n;
00072 }
00073
00074
00075 virtual double rand01()
00076 {
00077 if (!init)
00078 {
00079 initialize();
00080 init = true;
00081 }
00082
00083 return (double) randgen_sys_rand() / RAND_MAX;
00084 }
00085
00086
00087 virtual double randG()
00088 {
00089 if (!init)
00090 {
00091 initialize();
00092 init = true;
00093 }
00094
00095 if (hasNextG)
00096 {
00097 hasNextG = false;
00098 return nextG;
00099 }
00100 else
00101 {
00102 float x1, x2, w, y1, y2;
00103 do
00104 {
00105 x1 = 2.0 * rand01() - 1.0;
00106 x2 = 2.0 * rand01() - 1.0;
00107 w = x1 * x1 + x2 * x2;
00108 } while (w >= 1.0);
00109
00110 w = sqrt((-2.0 * log(w)) / w);
00111 y1 = x1 * w;
00112 y2 = x2 * w;
00113 nextG = y2;
00114 hasNextG = true;
00115 return y1;
00116 }
00117 }
00118
00119
00120 long getSeed()
00121 {
00122 return seed;
00123 }
00124
00125 template<class T>
00126 void shuffle(vector<T>& v)
00127 {
00128 for (int i = 0; i < v.size() - 1; i++)
00129 {
00130 int x = i + rand(v.size() - i - 1) + 1;
00131 T elem = v.at(i);
00132 v.at(i) = v.at(x);
00133 v.at(x) = elem;
00134 }
00135 }
00136
00137 };
00138
00139 #endif