-
Notifications
You must be signed in to change notification settings - Fork 0
/
tbx.rand.h
463 lines (444 loc) · 20.5 KB
/
tbx.rand.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#ifndef TBX_RAND_H
#define TBX_RAND_H
//================================================================================
// "MIT License"
//================================================================================
// Copyright 2023 Michael J. Mannon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//================================================================================
//======================================================================
// tbx.rand.h
//======================================================================
// This header provides drop-in replacements for functions std::rand()
// and std::srand(seed) from standard library header <cstdlib>.
//
// When used without template arguments, rand() and srand(seed)
// duplicate the interface and semantics of the corresponding functions
// in <cstdlib>:
//
// • tbx::rand() returns a pseudo-random int on the closed interval
// [0, tbx::rand_max()].
//
// • tbx::srand(seed) accepts an unsigned int as its argument, and
// uses it to seed the std::mt19937 random number engine that
// underlies rand().
//
// • tbx::rand() is implicitly seeded as if tbx::srand(1u) had been
// called.
//
// Template parameter ResultType controls the type of the random
// numbers generated by rand(). It can be any of the types accepted
// by std::uniform_int_distribution or std::uniform_real_distribution,
// as well as their many type aliases from <cstdint>.
//
// ResultType can also be bool, char, signed char or unsigned char.
//
// Here are some examples:
//
// • tbx::rand<bool>() • tbx::rand<unsigned char>()
// • tbx::rand<short>() • tbx::rand<float>()
// • tbx::rand<unsigned long long>() • tbx::rand<double>()
// • tbx::rand<std::int64_t>() • etc.
//
// Two non-standard overloads limit the range of values generated
// by rand():
//
// • tbx::rand(a, b) generate values on the integral range [a, b]
// or the floating-point range [a, b)
//
// • tbx::rand(param) "parameter" object of type
// std::uniform_int_distribution::param_type
// or std::uniform_real_distribution::param_type
//
// Two non-standard overloads provide alternate seeding options, both
// superior to srand(seed):
//
// • tbx::srand() Use std::random_device to fill all 624 state
// variables of std::mt19937.
//
// • tbx::rand(seed_seq) Use a std::seed_seq to fill all 624 state
// variables of std::mt19937.
//
// Behind the scenes, rand(), srand(seed) and rand_max(), along with
// the four overloads described above, share a common random number
// engine and distribution.
//
// The engine is std::mt19937.
//
// The distribution varies, depending on ResultType. For integral
// types, the distribution is std::uniform_int_distribution. For
// floating-point, std::uniform_real_distribution.
//
// Thread Safe: All functions are "thread_local," meaning that each
// thread where rand() is called has a random number engine and
// distribution of its own. Threads that call functions in the rand()
// family do not contend with other threads that use rand(), so no
// locking is necessary.
//
// Lazy Initialization: The random number generator in a given thread
// is not initialized until one of the functions in the rand() family
// is called in that thread. Thus, you don't pay for what you don't use.
//
//======================================================================
// IMPORTANT NOTE: Any template argument used by rand() must also be
// used by srand() and the other functions in the rand() family.
//
// If, for instance, you generate random numbers using
// tbx::rand<unsigned short>(), then you must seed the generator
// using tbx::srand<unsigned short>() or one of its overloads.
// Otherwise, you will seed a different engine from the one you intend.
//
// Each ResultType has its own random number engine. To select an
// engine for seeding, you MUST provide its ResultType. The only
// exception is when ResultType is int. Without a template arguemtnt,
// srand() and its overloads default to seeding the random number
// engine for type int.
//======================================================================
#include <array> // array
#include <cstddef> // size_t
#include <cstdint> // uint_fast16_t, uint_least32_t
#include <initializer_list> // initializer_list
#include <iterator> // interator_traits
#include <limits> // numeric_limits
#include <random> // mt19937, random_device, seed_seq, uniform_int_distribution, uniform_real_distribution
#include <sstream> // stringstream
#include <stdexcept> // invalid_argument
#include <type_traits> // enable_if_t, integral_constant, is_floating_point_v, is_integral_v,
// is_same_v, remove_cv_t, is_unsigned_v
namespace tbx
{
//==================================================================
// is_bool_or_char
//==================================================================
template <typename T>
struct is_bool_or_char : std::integral_constant
< bool
, std::is_same_v<std::remove_cv_t<T>, bool>
|| std::is_same_v<std::remove_cv_t<T>, char>
|| std::is_same_v<std::remove_cv_t<T>, signed char>
|| std::is_same_v<std::remove_cv_t<T>, unsigned char>
>
{};
template <typename T>
bool constexpr is_bool_or_char_v = tbx::is_bool_or_char<T>::value;
//==================================================================
// is_integral_short_int_long
//==================================================================
template <typename T>
struct is_integral_short_int_long : std::integral_constant
< bool
, std::is_same_v<std::remove_cv_t<T>, short>
|| std::is_same_v<std::remove_cv_t<T>, int>
|| std::is_same_v<std::remove_cv_t<T>, long>
|| std::is_same_v<std::remove_cv_t<T>, long long>
|| std::is_same_v<std::remove_cv_t<T>, unsigned short>
|| std::is_same_v<std::remove_cv_t<T>, unsigned int>
|| std::is_same_v<std::remove_cv_t<T>, unsigned long>
|| std::is_same_v<std::remove_cv_t<T>, unsigned long long>
>
{};
template <typename T>
bool constexpr is_integral_short_int_long_v
= tbx::is_integral_short_int_long<T>::value;
//==================================================================
// is_integral
//==================================================================
template <typename T>
struct is_integral : std::integral_constant
< bool
, tbx::is_integral_short_int_long_v<T> || tbx::is_bool_or_char_v<T>
>
{};
template <typename T>
bool constexpr is_integral_v = tbx::is_integral<T>::value;
//==================================================================
// is_arithmetic_short_int_long
//==================================================================
template <typename T>
struct is_arithmetic_short_int_long : std::integral_constant
< bool
, tbx::is_integral_short_int_long_v<T> || std::is_floating_point_v<T>
>
{};
template <typename T>
bool constexpr is_arithmetic_short_int_long_v
= tbx::is_arithmetic_short_int_long<T>::value;
//==================================================================
// is_arithmetic
//==================================================================
template <typename T>
struct is_arithmetic : std::integral_constant
< bool
, tbx::is_integral_v<T> || std::is_floating_point_v<T>
>
{};
template <typename T>
bool constexpr is_arithmetic_v = tbx::is_arithmetic<T>::value;
//==================================================================
// distribution_result
//==================================================================
template <typename ResultType, typename = void>
struct distribution_result {
static_assert(tbx::is_arithmetic_short_int_long_v<ResultType>, "");
using type = ResultType;
};
template <typename ResultType>
struct distribution_result<ResultType, std::enable_if_t<tbx::is_bool_or_char_v<ResultType>>> {
using type = std::int_fast16_t;
};
template <typename ResultType>
using distribution_result_t = typename tbx::distribution_result<ResultType>::type;
//==================================================================
// uniform_distribution
//==================================================================
template <typename ResultType, typename = void>
struct uniform_distribution {
static_assert(tbx::is_integral_v<ResultType>, "");
using type = std::uniform_int_distribution<tbx::distribution_result_t<ResultType>>;
};
template <typename ResultType>
struct uniform_distribution<ResultType, std::enable_if_t<std::is_floating_point_v<ResultType>>> {
using type = std::uniform_real_distribution<ResultType>;
};
template <typename ResultType>
using uniform_distribution_t = typename tbx::uniform_distribution<ResultType>::type;
//==================================================================
// param_type
//==================================================================
template <typename ResultType>
using param_type = typename tbx::uniform_distribution_t<ResultType>::param_type;
//==================================================================
// seed_seq_rd
//==================================================================
class seed_seq_rd
{
// This class mimics the interface of std::seed_seq, but
// uses std::random_device to generate seeds.
//
// It performs only minimal checking of its template arguments.
// Other than that, it complies with all requirements of a seed
// sequence as defined in the C++ standard.
public:
using result_type = typename std::random_device::result_type;
private:
// No matter what ctor you use, all you get is this array
// with one element. Best practice, therefore, is to use the
// default ctor.
enum : std::size_t { zero, one };
std::array<result_type, one> seeds{};
public:
seed_seq_rd() noexcept
= default;
template< typename InputIt >
seed_seq_rd(InputIt begin, InputIt end) {
using value_type = typename std::iterator_traits<InputIt>::value_type;
static_assert(std::is_integral_v<value_type>, "");
}
template< typename T >
seed_seq_rd(std::initializer_list<T> li) {
using value_type = typename std::initializer_list<T>::value_type;
static_assert(std::is_integral_v<value_type>, "");
}
seed_seq_rd(seed_seq_rd const&)
= delete;
seed_seq_rd& operator=(seed_seq_rd const&)
= delete;
template< typename RandomIt >
void generate(RandomIt begin, RandomIt end) {
using value_type = typename std::iterator_traits<RandomIt>::value_type;
static_assert(std::is_integral_v<value_type>, "");
static_assert(std::is_unsigned_v<value_type>, "");
static_assert(sizeof(value_type) >= sizeof(std::uint_least32_t), "");
std::random_device rd;
while (begin != end)
*begin++ = rd();
}
template <typename OutputIt>
void param(OutputIt dest) const {
*dest = seeds.front();
}
auto size() const noexcept {
return seeds.size();
}
};
//==================================================================
// rand_replacement
//==================================================================
template <typename ResultType, typename = void>
class rand_replacement
{
static_assert(tbx::is_arithmetic_short_int_long_v<ResultType>, "");
public:
using urbg_type = std::mt19937;
using seed_type = typename std::mt19937::result_type;
using distribution_type = tbx::uniform_distribution_t<ResultType>;
using param_type = typename distribution_type::param_type;
using result_type = ResultType;
private:
urbg_type eng_{ default_seed };
distribution_type dist_;
public:
auto static constexpr const default_seed{ seed_type{1u} };
// Drop-in replacements for rand(), RAND_MAX, and srand(seed)
auto rand() { return dist_(eng_); }
auto rand_max() { return dist_.max(); }
void srand(seed_type const seed) { dist_.reset(); eng_.seed(seed); }
// Non-standard overloads
void srand() { dist_.reset(); tbx::seed_seq_rd s; eng_.seed(s); }
void srand(std::seed_seq const& sseq) { dist_.reset(); eng_.seed(sseq); }
auto rand(param_type const& p) { return dist_(eng_, p); }
auto rand(result_type const a, result_type const b) {
return dist_(eng_, make_param(a, b));
}
private:
auto static constexpr make_param(result_type const a, result_type const b)
{
return param_type
{
a < b ? param_type{ a, b }
: b < a ? param_type{ b, a }
: tbx::is_integral_short_int_long_v<ResultType> ? param_type{ a, b }
: throw std::invalid_argument(
"tbx::rand_replacement<ResultType>::make_param(a, b): "
"floating-point arguments require a != b")
};
}
};
//==================================================================
// rand_replacement - specialization for bool and char types
//==================================================================
template <typename ResultType>
class rand_replacement<ResultType, std::enable_if_t<tbx::is_bool_or_char_v<ResultType>>>
{
public:
using urbg_type = std::mt19937;
using seed_type = typename std::mt19937::result_type;
using distribution_type = tbx::uniform_distribution_t<ResultType>;
using param_type = typename distribution_type::param_type;
using result_type = ResultType;
private:
auto static constexpr drt(result_type const r) {
return static_cast<tbx::distribution_result_t<result_type>>(r);
}
auto static constexpr rt(tbx::distribution_result_t<result_type> const r) {
return static_cast<result_type>(r);
}
auto static constexpr rt_max() {
return std::numeric_limits<result_type>::max();
}
auto static constexpr rt_min() {
return std::numeric_limits<result_type>::min();
}
auto static constexpr rt_default_b() {
return std::is_floating_point_v<result_type> ? result_type{ 1 } : rt_max();
}
urbg_type eng_{ default_seed };
distribution_type dist_{ drt(result_type{}), drt(rt_default_b()) };
public:
auto static constexpr const default_seed{ seed_type{1u} };
// Drop-in replacements for rand(), RAND_MAX, and srand(seed)
auto rand() { return rt(dist_(eng_)); }
auto rand_max() { return rt_max(); }
void srand(seed_type const seed) { dist_.reset(); eng_.seed(seed); }
// Non-standard overloads
void srand() { dist_.reset(); tbx::seed_seq_rd s; eng_.seed(s); }
void srand(std::seed_seq const& sseq) { dist_.reset(); eng_.seed(sseq); }
auto rand(param_type const& p) { check(p); return rt(dist_(eng_, p)); }
auto rand(result_type const a, result_type const b) {
return rt(dist_(eng_, make_param(a, b)));
}
private:
void static constexpr check(param_type const& params) {
if (params.a() < drt(rt_min()) || drt(rt_max()) < params.b())
throw std::invalid_argument(
"tbx::rand_replacement<ResultType>::check(params): "
"params out of range for bool or char arguments");
}
auto static constexpr make_param(result_type const a, result_type const b) {
auto const aa{ drt(a) };
auto const bb{ drt(b) };
return a < b ? param_type{ aa, bb } : param_type{ bb, aa };
}
};
//==================================================================
// rr - "rand replacement"
//==================================================================
template <typename ResultType>
inline auto& rr()
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
static thread_local tbx::rand_replacement<ResultType> r;
return r;
}
//==================================================================
// rand(), srand(), etc.
//==================================================================
template <typename ResultType = int>
inline auto rand()
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
return tbx::rr<ResultType>().rand();
}
//------------------------------------------------------------------
template <typename ResultType = int>
inline auto rand(ResultType const a, ResultType const b)
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
return tbx::rr<ResultType>().rand(a, b);
}
//------------------------------------------------------------------
template <typename ResultType = int>
inline auto rand(tbx::param_type<ResultType> const p)
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
return tbx::rr<ResultType>().rand(p);
}
//------------------------------------------------------------------
template <typename ResultType = int>
inline auto rand_max()
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
return tbx::rr<ResultType>().rand_max();
}
//------------------------------------------------------------------
template <typename ResultType = int>
inline void srand()
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
tbx::rr<ResultType>().srand(); // seed randomly from std::random_device
}
//------------------------------------------------------------------
template <typename ResultType = int>
inline void srand(typename std::mt19937::result_type const seed)
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
tbx::rr<ResultType>().srand(seed); // seed from unsigned int
}
//------------------------------------------------------------------
template <typename ResultType = int>
inline void srand(std::seed_seq const& sseq)
{
static_assert(tbx::is_arithmetic_v<ResultType>, "");
tbx::rr<ResultType>().srand(sseq); // seed from std::seed_seq
}
//------------------------------------------------------------------
} // end namespace tbx
#endif // TBX_RAND_H
// end file: tbx.rand.h