-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.hpp
1749 lines (1567 loc) · 71.2 KB
/
random.hpp
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
A way to use:
using Random = effolkronium::random_static;
*/
/*
______ ___ _ _______ ________ __
| ___ \/ _ \ | \ | | _ \ _ | \/ | Random for modern C++
| |_/ / /_\ \| \| | | | | | | | . . |
| /| _ || . ` | | | | | | | |\/| | version 1.4.1
| |\ \| | | || |\ | |/ /\ \_/ / | | |
\_| \_\_| |_/\_| \_/___/ \___/\_| |_/ https://github.com/effolkronium/random
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright (c) 2017-2022 effolkronium (Illia Polishchuk)
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.
*/
#ifndef EFFOLKRONIUM_RANDOM_HPP
#define EFFOLKRONIUM_RANDOM_HPP
#include <random>
#include <chrono> // timed seed
#include <type_traits>
#include <cassert>
#include <initializer_list>
#include <utility> // std::forward, std::declval
#include <algorithm> // std::shuffle, std::next, std::distance
#include <iterator> // std::begin, std::end, std::iterator_traits
#include <limits> // std::numeric_limits
#include <ostream>
#include <istream>
namespace effolkronium {
namespace details {
/// Key type for getting common type numbers or objects
struct common{ };
/// True if type T is applicable by a std::uniform_int_distribution
template<typename T>
struct is_uniform_int {
static constexpr bool value =
std::is_same<T, short>::value
|| std::is_same<T, int>::value
|| std::is_same<T, long>::value
|| std::is_same<T, long long>::value
|| std::is_same<T, unsigned short>::value
|| std::is_same<T, unsigned int>::value
|| std::is_same<T, unsigned long>::value
|| std::is_same<T, unsigned long long>::value;
};
/// True if type T is applicable by a std::uniform_real_distribution
template<typename T>
struct is_uniform_real {
static constexpr bool value =
std::is_same<T, float>::value
|| std::is_same<T, double>::value
|| std::is_same<T, long double>::value;
};
/// True if type T is plain byte
template<typename T>
struct is_byte {
static constexpr bool value =
std::is_same<T, signed char>::value
|| std::is_same<T, unsigned char>::value;
};
/// True if type T is plain number type
template<typename T>
struct is_supported_number {
static constexpr bool value =
is_byte <T>::value
|| is_uniform_real<T>::value
|| is_uniform_int <T>::value;
};
/// True if type T is character type
template<typename T>
struct is_supported_character {
static constexpr bool value =
std::is_same<T, char>::value
|| std::is_same<T, wchar_t>::value
|| std::is_same<T, char16_t>::value
|| std::is_same<T, char32_t>::value;
};
/// True if type T is iterator
template<typename T>
struct is_iterator {
private:
static char test( ... );
template <typename U,
typename = typename std::iterator_traits<U>::difference_type,
typename = typename std::iterator_traits<U>::pointer,
typename = typename std::iterator_traits<U>::reference,
typename = typename std::iterator_traits<U>::value_type,
typename = typename std::iterator_traits<U>::iterator_category
> static long test( U&& );
public:
static constexpr bool value = std::is_same<
decltype( test( std::declval<T>( ) ) ), long>::value;
};
template <typename T>
class has_reserve
{
private:
template <typename C>
static char test(...);
template <typename C>
static long test(decltype(&C::reserve));
public:
static constexpr bool value = std::is_same<
decltype(test<T>(0)), long>::value;
};
template <typename T>
class has_insert
{
private:
template <typename C>
static char test(...);
template <typename C>
static long test(decltype(&C::insert));
public:
static constexpr bool value = std::is_same<
decltype(test<T>(0)), long>::value;
};
} // namespace details
/// Default seeder for 'random' classes
struct seeder_default {
/// return seed sequence
std::seed_seq& operator() ( ) {
// MinGW issue, std::random_device returns constant value
// Use std::seed_seq with additional seed from C++ chrono
return seed_seq;
}
private:
std::seed_seq seed_seq{ {
static_cast<std::uintmax_t>( std::random_device{ }( ) ),
static_cast<std::uintmax_t>( std::chrono::steady_clock::now( )
.time_since_epoch( ).count( ) ),
} };
};
/**
* \brief Base template class for random
* with static API and static internal member storage
* \note it is NOT thread safe but more efficient then
* basic_random_thread_local
* \param Engine A random engine with interface like in the std::mt19937
* \param Seeder A seeder type which return seed for internal engine
* through operator()
*/
template<
typename Engine,
typename Seeder = seeder_default,
template<typename> class IntegerDist = std::uniform_int_distribution,
template<typename> class RealDist = std::uniform_real_distribution,
typename BoolDist = std::bernoulli_distribution
>
class basic_random_static {
public:
basic_random_static( ) = delete;
/// Type of used random number engine
using engine_type = Engine;
/// Type of used random number seeder
using seeder_type = Seeder;
/// Type of used integer distribution
template<typename T>
using integer_dist_t = IntegerDist<T>;
/// Type of used real distribution
template<typename T>
using real_dist_t = RealDist<T>;
/// Type of used bool distribution
using bool_dist_t = BoolDist;
/// Key type for getting common type numbers or objects
using common = details::common;
/**
* \return The minimum value
* potentially generated by the random-number engine
*/
static constexpr typename Engine::result_type (min)( ) {
return (Engine::min)( );
}
/**
* \return The maximum value
* potentially generated by the random-number engine
*/
static constexpr typename Engine::result_type (max)( ) {
return (Engine::max)( );
}
/// Advances the internal state by z times
static void discard( const unsigned long long z ) {
engine_instance( ).discard( z );
}
/// Reseed by Seeder
static void reseed( ) {
Seeder seeder;
seed( seeder( ) );
}
/**
* \brief Reinitializes the internal state
* of the random-number engine using new seed value
* \param value The seed value to use
* in the initialization of the internal state
*/
static void seed( const typename Engine::result_type value =
Engine::default_seed ) {
engine_instance( ).seed( value );
}
/**
* \brief Reinitializes the internal state
* of the random-number engine using new seed value
* \param seq The seed sequence
* to use in the initialization of the internal state
*/
template<typename Sseq>
static void seed( Sseq& seq ) {
engine_instance( ).seed( seq );
}
/// return random number from engine in [min(), max()] range
static typename Engine::result_type get( ) {
return engine_instance( )( );
}
/**
* \brief Compares internal pseudo-random number engine
* with 'other' pseudo-random number engine.
* Two engines are equal, if their internal states
* are equivalent, that is, if they would generate
* equivalent values for any number of calls of operator()
* \param other The engine, with which the internal engine will be compared
* \return true, if other and internal engine are equal
*/
static bool is_equal( const Engine& other ) {
return engine_instance( ) == other;
}
/**
* \brief Serializes the internal state of the
* internal pseudo-random number engine as a sequence
* of decimal numbers separated by one or more spaces,
* and inserts it to the stream ost. The fill character
* and the formatting flags of the stream are
* ignored and unaffected.
* \param ost The output stream to insert the data to
*/
template<typename CharT, typename Traits>
static void serialize( std::basic_ostream<CharT, Traits>& ost ) {
ost << engine_instance( );
}
/**
* \brief Restores the internal state of the
* internal pseudo-random number engine from
* the serialized representation, which
* was created by an earlier call to 'serialize'
* using a stream with the same imbued locale and
* the same CharT and Traits.
* If the input cannot be deserialized,
* internal engine is left unchanged and failbit is raised on ist
* \param ost The input stream to extract the data from
*/
template<typename CharT, typename Traits>
static void deserialize( std::basic_istream<CharT, Traits>& ist ) {
ist >> engine_instance( );
}
/**
* \brief Generate a random integer number in a [from; to] range
* by std::uniform_int_distribution
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random integer number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_uniform_int<T>::value
, T>::type get( T from = (std::numeric_limits<T>::min)( ),
T to = (std::numeric_limits<T>::max)( ) ) {
if( from < to ) // Allow range from higher to lower
return IntegerDist<T>{ from, to }( engine_instance( ) );
return IntegerDist<T>{ to, from }( engine_instance( ) );
}
/**
* \brief Generate a random real number in a [from; to] range
* by std::uniform_real_distribution
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random real number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_uniform_real<T>::value
, T>::type get( T from = (std::numeric_limits<T>::min)( ),
T to = (std::numeric_limits<T>::max)( ) ) {
if( from < to ) // Allow range from higher to lower
return RealDist<T>{ from, to }( engine_instance( ) );
return RealDist<T>{ to, from }( engine_instance( ) );
}
/**
* \brief Generate a random byte number in a [from; to] range
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random byte number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_byte<T>::value
, T>::type get( T from = (std::numeric_limits<T>::min)( ),
T to = (std::numeric_limits<T>::max)( ) ) {
// Choose between short and unsigned short for byte conversion
using short_t = typename std::conditional<std::is_signed<T>::value,
short, unsigned short>::type;
return static_cast<T>( get<short_t>( from, to ) );
}
/**
* \brief Generate a random common_type number in a [from; to] range
* \param Key The Key type for this version of 'get' method
* Type should be '(THIS_TYPE)::common' struct
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random common_type number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Allow implicit type conversion
* \note Prevent implicit type conversion from singed to unsigned types
* Why? std::common_type<Unsigned, Signed> chooses unsigned value,
* then Signed value will be converted to Unsigned value
* which gives us a wrong range for random values.
* https://stackoverflow.com/a/5416498/5734836
*/
template<
typename Key,
typename A,
typename B,
typename C = typename std::common_type<A, B>::type
>
static typename std::enable_if<
std::is_same<Key, common>::value
&& details::is_supported_number<A>::value
&& details::is_supported_number<B>::value
// Prevent implicit type conversion from singed to unsigned types
&& std::is_signed<A>::value != std::is_unsigned<B>::value
, C>::type get( A from = (std::numeric_limits<A>::min)( ),
B to = (std::numeric_limits<B>::max)( ) ) {
return get( static_cast<C>( from ), static_cast<C>( to ) );
}
/**
* \brief Generate a random character in a [from; to] range
* by std::uniform_int_distribution
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random character in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_supported_character<T>::value
, T>::type get(T from = (std::numeric_limits<T>::min)(),
T to = (std::numeric_limits<T>::max)()) {
if (from < to) // Allow range from higher to lower
return static_cast<T>(IntegerDist<std::int64_t>{ static_cast<std::int64_t>(from), static_cast<std::int64_t>(to) }(engine_instance()));
return static_cast<T>(IntegerDist<std::int64_t>{ static_cast<std::int64_t>(to), static_cast<std::int64_t>(from) }(engine_instance()));
}
/**
* \brief Generate a bool value with specific probability
* by std::bernoulli_distribution
* \param probability The probability of generating true in [0; 1] range
* 0 means always false, 1 means always true
* \return 'true' with 'probability' probability ('false' otherwise)
*/
template<typename T>
static typename std::enable_if<std::is_same<T, bool>::value
, bool>::type get( const double probability = 0.5 ) {
assert( 0 <= probability && 1 >= probability ); // out of [0; 1] range
return BoolDist{ probability }( engine_instance( ) );
}
/**
* \brief Return random value from initilizer_list
* \param init_list initilizer_list with values
* \return Random value from initilizer_list
* \note Should be 1 or more elements in initilizer_list
* \note Warning! Elements in initilizer_list can't be moved:
* https://stackoverflow.com/a/8193157/5734836
*/
template<typename T>
static T get( std::initializer_list<T> init_list ) {
assert( 0u != init_list.size( ) );
return *get( init_list.begin( ), init_list.end( ) );
}
/**
* \brief Return random iterator from iterator range
* \param first, last - the range of elements
* \return Random iterator from [first, last) range
* \note If first == last, return last
*/
template<typename InputIt>
static typename std::enable_if<details::is_iterator<InputIt>::value
, InputIt>::type get( InputIt first, InputIt last ) {
const auto size = std::distance( first, last );
if( 0 == size ) return last;
using diff_t = typename std::iterator_traits<InputIt>::difference_type;
return std::next( first, get<diff_t>( 0, size - 1 ) );
}
/**
* \brief Return random iterator from Container
* \param container The container with elements
* \return Random iterator from container
* \note If container is empty return std::end( container ) iterator
*/
template<typename Container>
static auto get( Container& container ) ->
typename std::enable_if<details::is_iterator<
decltype(std::begin(container))>::value
, decltype(std::begin(container))
>::type {
return get( std::begin( container ), std::end( container ) );
}
/**
* \brief Return container filled with random values
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param size The number of elements in resulting container
* \return Container filled with random values
* \note Container "reserve" method will be called before generation
*/
template<template<typename...> class Container, typename A>
static typename std::enable_if<
details::has_reserve<Container<A>>::value
, Container<A>>::type get(A from, A to, std::size_t size) {
Container<A> container;
container.reserve(size);
for (std::size_t i = 0; i < size; ++i)
container.insert(std::end(container), get(from, to));
return container;
}
/**
* \brief Return container filled with random common_type values
* \param Key The Key type for this version of 'get' method
* Type should be '(THIS_TYPE)::common' struct
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param size The number of elements in resulting container
* \return Container filled with random values
* \note Container "reserve" method will be called before generation
*/
template<
template<typename...> class Container,
typename Key,
typename A,
typename B,
typename C = typename std::common_type<A, B>::type>
static typename std::enable_if<
std::is_same<Key, common>::value
&& details::has_reserve<Container<A>>::value
, Container<C>>::type get(A start, B end, std::size_t size) {
Container<C> container;
container.reserve(size);
for (std::size_t i = 0; i < size; ++i)
container.insert(std::end(container), get<common>(start, end));
return container;
}
/**
* \brief Return container filled with random values
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param size The number of elements in resulting container
* \return Container filled with random values
*/
template<template<typename...> class Container, typename A>
static typename std::enable_if<
!details::has_reserve<Container<A>>::value
, Container<A>>::type get(A start, A end, std::size_t size) {
Container<A> container;
for (std::size_t i = 0; i < size; ++i)
container.insert(std::end(container), get(start, end));
return container;
}
/**
* \brief Return container filled with random common_type values
* \param Key The Key type for this version of 'get' method
* Type should be '(THIS_TYPE)::common' struct
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param size The number of elements in resulting container
* \return Container filled with random values
*/
template<
template<typename...> class Container,
typename Key,
typename A,
typename B,
typename C = typename std::common_type<A, B>::type>
static typename std::enable_if<
std::is_same<Key, common>::value
&& !details::has_reserve<Container<C>>::value
, Container<C>>::type get(A start, B end, std::size_t size) {
Container<C> container;
for (std::size_t i = 0; i < size; ++i)
container.insert(std::end(container), get<common>(start, end));
return container;
}
/**
* \brief Return array-like container filled with random values
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param N The number of elements in resulting container
* \return Container filled with random values
*/
template<template<typename AA, std::size_t NN, typename...> class Container, std::size_t N, typename A>
static typename std::enable_if<
!details::has_insert<Container<A, N>>::value
, Container<A, N>>::type get(A start, A end) {
Container<A, N> container = {{ 0 }};
for (std::size_t i = 0; i < N; ++i)
container[i] = get(start, end);
return container;
}
/**
* \brief Return array-like container filled with random common_type values
* \param Key The Key type for this version of 'get' method
* Type should be '(THIS_TYPE)::common' struct
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param size The number of elements in resulting container
* \return Container filled with random values
*/
template<
template<typename AA, std::size_t NN, typename...> class Container,
std::size_t N,
typename Key,
typename A,
typename B,
typename C = typename std::common_type<A, B>::type>
static typename std::enable_if<
std::is_same<Key, common>::value
&& !details::has_insert<Container<C, N>>::value
, Container<C, N>>::type get(A start, B end) {
Container<C, N> container = {{ 0 }};
for (std::size_t i = 0; i < N; ++i)
container[i] = get<common>(start, end);
return container;
}
/**
* \brief Return random pointer from built-in array
* \param array The built-in array with elements
* \return Pointer to random element in array
*/
template<typename T, std::size_t N>
static T* get( T( &array )[ N ] ) {
return std::addressof( array[ get<std::size_t>( 0, N - 1 ) ] );
}
/**
* \brief Return value from custom Dist distribution
* seeded by internal random engine
* \param Dist The type of custom distribution with next concept:
* http://en.cppreference.com/w/cpp/concept/RandomNumberDistribution
* \param args The arguments which will be forwarded to Dist constructor
* \return Value from custom distribution
*/
template<typename Dist, typename... Args>
static typename Dist::result_type get( Args&&... args ) {
return Dist{ std::forward<Args>( args )... }( engine_instance( ) );
}
/**
* \brief Return value from custom 'dist' distribution
* seeded by internal random engine
* \param dist The custom distribution with next concept:
* http://en.cppreference.com/w/cpp/concept/RandomNumberDistribution
* \param args The arguments which will be forwarded to Dist constructor
* \return Value from custom 'dist' distribution
*/
template<typename Dist>
static typename Dist::result_type get( Dist& dist ) {
return dist( engine_instance( ) );
}
/**
* \brief Reorders the elements in the given range [first, last)
* such that each possible permutation of those elements
* has equal probability of appearance.
* \param first, last - the range of elements to shuffle randomly
*/
template<typename RandomIt>
static void shuffle( RandomIt first, RandomIt last ) {
std::shuffle( first, last, engine_instance( ) );
}
/**
* \brief Reorders the elements in the given container
* such that each possible permutation of those elements
* has equal probability of appearance.
* \param container - the container with elements to shuffle randomly
*/
template<typename Container>
static void shuffle( Container& container ) {
shuffle( std::begin( container ), std::end( container ) );
}
/// return internal engine by copy
static Engine get_engine( ) {
return engine_instance( );
}
/// return internal engine by ref
static Engine& engine() {
return engine_instance();
}
protected:
/// get reference to the static engine instance
static Engine& engine_instance( ) {
static Engine engine{ Seeder{ }( ) };
return engine;
}
};
/**
* \brief Base template class for random
* with thread_local API and thread_local internal member storage
* \note it IS thread safe but less efficient then
* basic_random_static
* \param Engine A random engine with interface like in the std::mt19937
* \param Seeder A seeder type which return seed for internal engine
* through operator()
*/
template<
typename Engine,
typename Seeder = seeder_default,
template<typename> class IntegerDist = std::uniform_int_distribution,
template<typename> class RealDist = std::uniform_real_distribution,
typename BoolDist = std::bernoulli_distribution
>
class basic_random_thread_local {
public:
basic_random_thread_local( ) = delete;
/// Type of used random number engine
using engine_type = Engine;
/// Type of used random number seeder
using seeder_type = Seeder;
/// Type of used integer distribution
template<typename T>
using integer_dist_t = IntegerDist<T>;
/// Type of used real distribution
template<typename T>
using real_dist_t = RealDist<T>;
/// Type of used bool distribution
using bool_dist_t = BoolDist;
/// Key type for getting common type numbers or objects
using common = details::common;
/**
* \return The minimum value
* potentially generated by the random-number engine
*/
static constexpr typename Engine::result_type (min)( ) {
return (Engine::min)( );
}
/**
* \return The maximum value
* potentially generated by the random-number engine
*/
static constexpr typename Engine::result_type (max)( ) {
return (Engine::max)( );
}
/// Advances the internal state by z times
static void discard( const unsigned long long z ) {
engine_instance( ).discard( z );
}
/// Reseed by Seeder
static void reseed( ) {
Seeder seeder;
seed( seeder( ) );
}
/**
* \brief Reinitializes the internal state
* of the random-number engine using new seed value
* \param value The seed value to use
* in the initialization of the internal state
*/
static void seed( const typename Engine::result_type value =
Engine::default_seed ) {
engine_instance( ).seed( value );
}
/**
* \brief Reinitializes the internal state
* of the random-number engine using new seed value
* \param seq The seed sequence
* to use in the initialization of the internal state
*/
template<typename Sseq>
static void seed( Sseq& seq ) {
engine_instance( ).seed( seq );
}
/// return random number from engine in [min(), max()] range
static typename Engine::result_type get( ) {
return engine_instance( )( );
}
/**
* \brief Compares internal pseudo-random number engine
* with 'other' pseudo-random number engine.
* Two engines are equal, if their internal states
* are equivalent, that is, if they would generate
* equivalent values for any number of calls of operator()
* \param other The engine, with which the internal engine will be compared
* \return true, if other and internal engine are equal
*/
static bool is_equal( const Engine& other ) {
return engine_instance( ) == other;
}
/**
* \brief Serializes the internal state of the
* internal pseudo-random number engine as a sequence
* of decimal numbers separated by one or more spaces,
* and inserts it to the stream ost. The fill character
* and the formatting flags of the stream are
* ignored and unaffected.
* \param ost The output stream to insert the data to
*/
template<typename CharT, typename Traits>
static void serialize( std::basic_ostream<CharT, Traits>& ost ) {
ost << engine_instance( );
}
/**
* \brief Restores the internal state of the
* internal pseudo-random number engine from
* the serialized representation, which
* was created by an earlier call to 'serialize'
* using a stream with the same imbued locale and
* the same CharT and Traits.
* If the input cannot be deserialized,
* internal engine is left unchanged and failbit is raised on ist
* \param ost The input stream to extract the data from
*/
template<typename CharT, typename Traits>
static void deserialize( std::basic_istream<CharT, Traits>& ist ) {
ist >> engine_instance( );
}
/**
* \brief Generate a random integer number in a [from; to] range
* by std::uniform_int_distribution
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random integer number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_uniform_int<T>::value
, T>::type get( T from = (std::numeric_limits<T>::min)( ),
T to = (std::numeric_limits<T>::max)( ) ) {
if( from < to ) // Allow range from higher to lower
return IntegerDist<T>{ from, to }( engine_instance( ) );
return IntegerDist<T>{ to, from }( engine_instance( ) );
}
/**
* \brief Generate a random real number in a [from; to] range
* by std::uniform_real_distribution
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random real number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_uniform_real<T>::value
, T>::type get( T from = (std::numeric_limits<T>::min)( ),
T to = (std::numeric_limits<T>::max)( ) ) {
if( from < to ) // Allow range from higher to lower
return RealDist<T>{ from, to }( engine_instance( ) );
return RealDist<T>{ to, from }( engine_instance( ) );
}
/**
* \brief Generate a random byte number in a [from; to] range
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random byte number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_byte<T>::value
, T>::type get( T from = (std::numeric_limits<T>::min)( ),
T to = (std::numeric_limits<T>::max)( ) ) {
// Choose between short and unsigned short for byte conversion
using short_t = typename std::conditional<std::is_signed<T>::value,
short, unsigned short>::type;
return static_cast<T>( get<short_t>( from, to ) );
}
/**
* \brief Generate a random common_type number in a [from; to] range
* \param Key The Key type for this version of 'get' method
* Type should be '(THIS_TYPE)::common' struct
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random common_type number in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Allow implicit type conversion
* \note Prevent implicit type conversion from singed to unsigned types
* Why? std::common_type<Unsigned, Signed> chooses unsigned value,
* then Signed value will be converted to Unsigned value
* which gives us a wrong range for random values.
* https://stackoverflow.com/a/5416498/5734836
*/
template<
typename Key,
typename A,
typename B,
typename C = typename std::common_type<A, B>::type
>
static typename std::enable_if<
std::is_same<Key, common>::value
&& details::is_supported_number<A>::value
&& details::is_supported_number<B>::value
// Prevent implicit type conversion from singed to unsigned types
&& std::is_signed<A>::value != std::is_unsigned<B>::value
, C>::type get( A from = (std::numeric_limits<A>::min)( ),
B to = (std::numeric_limits<B>::max)( ) ) {
return get( static_cast<C>( from ), static_cast<C>( to ) );
}
/**
* \brief Generate a random character in a [from; to] range
* by std::uniform_int_distribution
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \return A random character in a [from; to] range
* \note Allow both: 'from' <= 'to' and 'from' >= 'to'
* \note Prevent implicit type conversion
*/
template<typename T>
static typename std::enable_if<details::is_supported_character<T>::value
, T>::type get(T from = (std::numeric_limits<T>::min)(),
T to = (std::numeric_limits<T>::max)()) {
if (from < to) // Allow range from higher to lower
return static_cast<T>(IntegerDist<std::int64_t>{ static_cast<std::int64_t>(from), static_cast<std::int64_t>(to) }(engine_instance()));
return static_cast<T>(IntegerDist<std::int64_t>{ static_cast<std::int64_t>(to), static_cast<std::int64_t>(from) }(engine_instance()));
}
/**
* \brief Generate a bool value with specific probability
* by std::bernoulli_distribution
* \param probability The probability of generating true in [0; 1] range
* 0 means always false, 1 means always true
* \return 'true' with 'probability' probability ('false' otherwise)
*/
template<typename T>
static typename std::enable_if<std::is_same<T, bool>::value
, bool>::type get( const double probability = 0.5 ) {
assert( 0 <= probability && 1 >= probability ); // out of [0; 1] range
return BoolDist{ probability }( engine_instance( ) );
}
/**
* \brief Return random value from initilizer_list
* \param init_list initilizer_list with values
* \return Random value from initilizer_list
* \note Should be 1 or more elements in initilizer_list
* \note Warning! Elements in initilizer_list can't be moved:
* https://stackoverflow.com/a/8193157/5734836
*/
template<typename T>
static T get( std::initializer_list<T> init_list ) {
assert( 0u != init_list.size( ) );
return *get( init_list.begin( ), init_list.end( ) );
}
/**
* \brief Return random iterator from iterator range
* \param first, last - the range of elements
* \return Random iterator from [first, last) range
* \note If first == last, return last
*/
template<typename InputIt>
static typename std::enable_if<details::is_iterator<InputIt>::value
, InputIt>::type get( InputIt first, InputIt last ) {
const auto size = std::distance( first, last );
if( 0 == size ) return last;
using diff_t = typename std::iterator_traits<InputIt>::difference_type;
return std::next( first, get<diff_t>( 0, size - 1 ) );
}
/**
* \brief Return random iterator from Container
* \param container The container with elements
* \return Random iterator from container
* \note If container is empty return std::end( container ) iterator
*/
template<typename Container>
static auto get( Container& container ) ->
typename std::enable_if<details::is_iterator<
decltype(std::begin(container))>::value
, decltype(std::begin(container))
>::type {
return get( std::begin( container ), std::end( container ) );
}
/**
* \brief Return container filled with random values
* \param from The first limit number of a random range
* \param to The second limit number of a random range
* \param size The number of elements in resulting container
* \return Container filled with random values
* \note Container "reserve" method will be called before generation
*/
template<template<typename...> class Container, typename A>
static typename std::enable_if<
details::has_reserve<Container<A>>::value
, Container<A>>::type get(A from, A to, std::size_t size) {