1//===----------------------------------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is dual licensed under the MIT and the University of Illinois Open 6// Source Licenses. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10// <random> 11 12// template<class Engine, size_t w, class UIntType> 13// class independent_bits_engine 14 15// result_type operator()(); 16 17#include <random> 18#include <cassert> 19 20template <class UIntType, UIntType Min, UIntType Max> 21class rand1 22{ 23public: 24 // types 25 typedef UIntType result_type; 26 27private: 28 result_type x_; 29 30 static_assert(Min < Max, "rand1 invalid parameters"); 31public: 32 33#ifdef _LIBCPP_HAS_NO_CONSTEXPR 34 // Workaround for lack of constexpr in C++03 35 static const result_type _Min = Min; 36 static const result_type _Max = Max; 37#endif 38 39 static _LIBCPP_CONSTEXPR result_type min() {return Min;} 40 static _LIBCPP_CONSTEXPR result_type max() {return Max;} 41 42 explicit rand1(result_type sd = Min) : x_(sd) 43 { 44 if (x_ > Max) 45 x_ = Max; 46 } 47 48 result_type operator()() 49 { 50 result_type r = x_; 51 if (x_ < Max) 52 ++x_; 53 else 54 x_ = Min; 55 return r; 56 } 57}; 58 59void 60test1() 61{ 62 typedef std::independent_bits_engine<rand1<unsigned, 0, 10>, 16, unsigned> E; 63 64 E e; 65 assert(e() == 6958); 66} 67 68void 69test2() 70{ 71 typedef std::independent_bits_engine<rand1<unsigned, 0, 100>, 16, unsigned> E; 72 73 E e; 74 assert(e() == 66); 75} 76 77void 78test3() 79{ 80 typedef std::independent_bits_engine<rand1<unsigned, 0, 0xFFFFFFFF>, 32, unsigned> E; 81 82 E e(5); 83 assert(e() == 5); 84} 85 86void 87test4() 88{ 89 typedef std::independent_bits_engine<rand1<unsigned, 0, 0xFFFFFFFF>, 7, unsigned> E; 90 91 E e(129); 92 assert(e() == 1); 93} 94 95void 96test5() 97{ 98 typedef std::independent_bits_engine<rand1<unsigned, 2, 3>, 1, unsigned> E; 99 100 E e(6); 101 assert(e() == 1); 102} 103 104void 105test6() 106{ 107 typedef std::independent_bits_engine<rand1<unsigned, 2, 3>, 11, unsigned> E; 108 109 E e(6); 110 assert(e() == 1365); 111} 112 113void 114test7() 115{ 116 typedef std::independent_bits_engine<rand1<unsigned, 2, 3>, 32, unsigned> E; 117 118 E e(6); 119 assert(e() == 2863311530u); 120} 121 122void 123test8() 124{ 125 typedef std::independent_bits_engine<std::mt19937, 64, unsigned long long> E; 126 127 E e(6); 128 assert(e() == 16470362623952407241ull); 129} 130 131int main() 132{ 133 test1(); 134 test2(); 135 test3(); 136 test4(); 137 test5(); 138 test6(); 139 test7(); 140 test8(); 141} 142