101 lines
2.0 KiB
C++
101 lines
2.0 KiB
C++
/**
|
||
* @file dl_random.h
|
||
* @brief 随机数
|
||
*
|
||
*
|
||
* @version 1.0
|
||
* @author lveyou
|
||
* @date 23-06-24
|
||
*/
|
||
#pragma once
|
||
|
||
#include <random>
|
||
#include "io/dl_log.h"
|
||
|
||
namespace dl
|
||
{
|
||
class Random
|
||
{
|
||
public:
|
||
/**
|
||
* @brief 设置随机数种子
|
||
* @note 0会随机生成一个种子
|
||
*/
|
||
static void SetSeed(uint32_t seed)
|
||
{
|
||
if (seed == 0)
|
||
{
|
||
std::random_device rd;
|
||
_re.seed(_seed = rd());
|
||
}
|
||
else
|
||
_re.seed(_seed = seed);
|
||
}
|
||
|
||
/**
|
||
* @brief 返回[min,max)区间的 浮点数随机值
|
||
* @note 如果min等于max,则返回min。如果min大于max则交换位置后比较,但会发出一条警告。
|
||
*/
|
||
template <typename T>
|
||
static T Float(T min, T max)
|
||
{
|
||
//参数检查
|
||
if (min > max)
|
||
{
|
||
log("min > max!");
|
||
std::swap(min, max);
|
||
}
|
||
static std::uniform_real_distribution<T> dist_double;
|
||
//设定区间
|
||
using D = std::decay_t<decltype(dist_double)>;
|
||
using P = typename D::param_type;
|
||
dist_double.param(P{min, max});
|
||
return dist_double(_re);
|
||
}
|
||
|
||
/**
|
||
* @brief 返回[min,max]区间的 随机整数
|
||
* @note 如果min等于max,则返回min。如果min大于max则交换位置后比较,但会发出一条警告。
|
||
*/
|
||
template <typename T>
|
||
static T Integer(T min, T max)
|
||
{
|
||
//参数检查
|
||
if (min > max)
|
||
{
|
||
log("min > max!");
|
||
std::swap(min, max);
|
||
}
|
||
static std::uniform_int_distribution<T> dist_int;
|
||
//设定区间
|
||
using D = std::decay_t<decltype(dist_int)>;
|
||
using P = typename D::param_type;
|
||
dist_int.param(P{min, max});
|
||
return dist_int(_re);
|
||
}
|
||
|
||
static bool Bool()
|
||
{
|
||
return Integer(0, 1) == 1;
|
||
}
|
||
|
||
/**
|
||
* @brief 从容器随机选择一个
|
||
* @param[in] container 容器(不能为空)
|
||
* @retval 返回引用
|
||
*/
|
||
template <typename C>
|
||
static auto& Select(C& container)
|
||
{
|
||
assert(!container.empty());
|
||
size_t index = Integer<size_t>(0, container.size() - 1);
|
||
auto iter = container.begin();
|
||
advance(iter, index);
|
||
return *iter;
|
||
}
|
||
private:
|
||
static uint32_t _seed;//! 种子值
|
||
static std::default_random_engine _re;//! 随机数序列生成器
|
||
};
|
||
}
|