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