dl
dl_random.h
浏览该文件的文档.
1
10#pragma once
11
12#include <random>
13#include "io/dl_log.h"
14
15namespace dl
16{
18class Random
19{
20public:
25 static void SetSeed(uint32_t seed)
26 {
27 if (seed == 0)
28 {
29 std::random_device rd;
30 _re.seed(_seed = rd());
31 }
32 else
33 _re.seed(_seed = seed);
34 }
35
40 template <typename T>
41 static T Float(T min, T max)
42 {
43 //参数检查
44 if (min > max)
45 {
46 log("min > max!");
47 std::swap(min, max);
48 }
49 static std::uniform_real_distribution<T> dist_double;
50 //设定区间
51 using D = std::decay_t<decltype(dist_double)>;
52 using P = typename D::param_type;
53 dist_double.param(P{min, max});
54 return dist_double(_re);
55 }
56
61 template <typename T>
62 static T Integer(T min, T max)
63 {
64 //参数检查
65 if (min > max)
66 {
67 log("min > max!");
68 std::swap(min, max);
69 }
70 static std::uniform_int_distribution<T> dist_int;
71 //设定区间
72 using D = std::decay_t<decltype(dist_int)>;
73 using P = typename D::param_type;
74 dist_int.param(P{min, max});
75 return dist_int(_re);
76 }
77
78 static bool Bool()
79 {
80 return Integer(0, 1) == 1;
81 }
82
86 static int Int(int min, int max)
87 {
88 return Integer(min, max);
89 }
90
93 static unsigned Uint(unsigned min, unsigned max)
94 {
95 return Integer(min, max);
96 }
97
103 template <typename C>
104 static auto& Select(C& container)
105 {
106 assert(!container.empty());
107 size_t index = Integer<size_t>(0, container.size() - 1);
108 auto iter = container.begin();
109 advance(iter, index);
110 return *iter;
111 }
112private:
113 static uint32_t _seed;
114 static std::default_random_engine _re;
115};
116}
随机数
static auto & Select(C &container)
从容器随机选择一个
static T Float(T min, T max)
返回[min,max)区间的 浮点数随机值
static T Integer(T min, T max)
返回[min,max]区间的 随机整数
static int Int(int min, int max)
返回[min,max]区间的 int型整数
static void SetSeed(uint32_t seed)
设置随机数种子
static bool Bool()
static unsigned Uint(unsigned min, unsigned max)
返回[min,max]区间的 unsigned型整数
日志系统
void log(std::string_view str, const std::source_location location=std::source_location::current())
以当前设置输出