1
1
/* -----------------------------------------------------------------------------------------------
2
2
The MIT License (MIT)
3
3
4
- Copyright (c) 2014-2024 Kim Kulling
4
+ Copyright (c) 2014-2025 Kim Kulling
5
5
6
6
Permission is hereby granted, free of charge, to any person obtaining a copy of
7
7
this software and associated documentation files (the "Software"), to deal in
@@ -28,21 +28,29 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
28
29
29
namespace cppcore {
30
30
31
- static const unsigned int N = 624 ;
32
- static const unsigned int M = 397 ;
31
+ static constexpr unsigned int N = 624 ;
32
+ static constexpr unsigned int M = 397 ;
33
33
34
- static void mersenne_twister_vector_init ( unsigned int *seedPoints, size_t len ) {
35
- assert ( nullptr != seedPoints );
34
+ static bool mersenne_twister_vector_init ( unsigned int *seedPoints, size_t len ) {
35
+ if (seedPoints == nullptr ) {
36
+ return false ;
37
+ }
36
38
37
39
const unsigned int mult = 1812433253ul ;
38
40
unsigned int seed = 5489ul ;
39
41
for (size_t i = 0 ; i < len; ++i) {
40
42
seedPoints[ i ] = seed;
41
43
seed = mult * (seed ^ (seed >> 30 )) + (static_cast <unsigned int >(i) + 1 );
42
44
}
45
+
46
+ return true ;
43
47
}
44
48
45
- static void mersenne_twister_vector_update (unsigned int * const p) {
49
+ static bool mersenne_twister_vector_update (unsigned int * const p) {
50
+ if (p == nullptr ) {
51
+ return false ;
52
+ }
53
+
46
54
static const unsigned int A[ 2 ] = { 0 , 0x9908B0DF };
47
55
unsigned int i=0 ;
48
56
for (; i < N - M; i++) {
@@ -52,6 +60,8 @@ static void mersenne_twister_vector_update(unsigned int* const p) {
52
60
p[i] = p[i + (M - N)] ^ (((p[i] & 0x80000000 ) | (p[i + 1 ] & 0x7FFFFFFF )) >> 1 ) ^ A[p[i + 1 ] & 1 ];
53
61
}
54
62
p[N - 1 ] = p[M - 1 ] ^ (((p[N - 1 ] & 0x80000000 ) | (p[0 ] & 0x7FFFFFFF )) >> 1 ) ^ A[p[0 ] & 1 ];
63
+
64
+ return true ;
55
65
}
56
66
57
67
unsigned int mersenne_twister () {
@@ -60,13 +70,15 @@ unsigned int mersenne_twister() {
60
70
// readout index
61
71
static int idx = N + 1 ;
62
72
73
+ bool ok = true ;
63
74
if (static_cast <unsigned int >(idx) >= N) {
64
75
if (static_cast <unsigned int >(idx) > N) {
65
- mersenne_twister_vector_init (vector, N);
76
+ ok &= mersenne_twister_vector_init (vector, N);
66
77
}
67
- mersenne_twister_vector_update (vector);
78
+ ok &= mersenne_twister_vector_update (vector);
68
79
idx = 0 ;
69
80
}
81
+ assert (ok);
70
82
unsigned int e = vector[ idx++ ];
71
83
72
84
// Tempering
@@ -80,7 +92,7 @@ unsigned int mersenne_twister() {
80
92
81
93
RandomGenerator::RandomGenerator ( GeneratorType type ) noexcept :
82
94
m_type ( type ) {
83
- ::srand ( static_cast <unsigned int >(time(nullptr )));
95
+ ::srand (static_cast <unsigned int >(time(nullptr )));
84
96
}
85
97
86
98
int RandomGenerator::get ( int lower, int upper ) {
0 commit comments