RSTools 3.1.0
Versatile C++20 utility library
Loading...
Searching...
No Matches
Random.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <random>
5#include <type_traits>
6#include <vector>
7
8namespace RST::Maths {
9
12
14 inline std::mt19937& randomEngine() {
15 thread_local std::mt19937 engine(std::random_device{}());
16 return engine;
17 }
18
20 template<typename T>
21 T random(const T& min, const T& max) {
22 static_assert(std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, "random needs a number type");
23
24 if constexpr (std::is_integral_v<T>) {
25 using Wide = std::conditional_t<std::is_signed_v<T>, long long, unsigned long long>;
26 std::uniform_int_distribution<Wide> dist(min, max);
27 return static_cast<T>(dist(randomEngine()));
28 } else {
29 std::uniform_real_distribution<T> dist(min, max);
30 return dist(randomEngine());
31 }
32 }
33
35 template<typename T>
36 T randomChoice(const std::vector<T>& list) {
37 if (list.empty())
38 return T{};
39
40 std::uniform_int_distribution<std::size_t> dist(0, list.size() - 1);
41 return list[dist(randomEngine())];
42 }
44
45}
Math helpers: constants, interpolation, random numbers, 2D and 3D vectors and matrices.
Definition Constants.hpp:5
T randomChoice(const std::vector< T > &list)
Random element of list, or T{} if it is empty.
Definition Random.hpp:36
std::mt19937 & randomEngine()
Per-thread engine behind random() and randomChoice(); call seed() on it for reproducible results.
Definition Random.hpp:14
T random(const T &min, const T &max)
Uniform random number in [min, max] for integers, or [min, max) for floating-point types.
Definition Random.hpp:21