00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040 namespace Gecode { namespace Support {
00041
00049 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00050 class LinearCongruentialGenerator {
00051 private:
00053 static const unsigned int max = 1UL<<31;
00055 unsigned int s;
00057 unsigned int next(void);
00058 public:
00060 void seed(unsigned int _s);
00062 LinearCongruentialGenerator(unsigned int _s = 1);
00064 unsigned int seed(void) const;
00066 unsigned int operator ()(unsigned int n);
00068 size_t size(void) const;
00069 };
00070
00071 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00072 forceinline unsigned int
00073 LinearCongruentialGenerator<m,a,q,r>::next(void) {
00074 s = a*(s%q) - r*(s/q);
00075 unsigned int res = s;
00076 if (s==0) s = 1;
00077 return res;
00078 }
00079 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00080 forceinline void
00081 LinearCongruentialGenerator<m,a,q,r>::seed(unsigned int _s) {
00082 s = _s % m;
00083 if (s == 0) s = 1;
00084 }
00085 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00086 forceinline
00087 LinearCongruentialGenerator<m,a,q,r>::
00088 LinearCongruentialGenerator(unsigned int _s) {
00089 seed(_s);
00090 }
00091 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00092 forceinline unsigned int
00093 LinearCongruentialGenerator<m,a,q,r>::seed(void) const {
00094 return s;
00095 }
00096 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00097 forceinline unsigned int
00098 LinearCongruentialGenerator<m,a,q,r>::operator ()(unsigned int n) {
00099 unsigned int x1 = next() & ((1<<16)-1);
00100 unsigned int x2 = next() & ((1<<16)-1);
00101 if (n < 2) return 0;
00102 double d = static_cast<double>(((x1<<16) | x2) % max) / max;
00103 unsigned int val = static_cast<unsigned int>(n * d);
00104 return (val < n) ? val : (n-1);
00105 }
00106 template<unsigned int m, unsigned int a, unsigned int q, unsigned int r>
00107 forceinline size_t
00108 LinearCongruentialGenerator<m,a,q,r>::size(void) const {
00109 return sizeof(LinearCongruentialGenerator<m,a,q,r>);
00110 }
00111
00112
00123 typedef LinearCongruentialGenerator<2147483647, 48271, 44488, 3399>
00124 RandomGenerator;
00125
00126 }}
00127
00128