CCIMXDesktop
 
Loading...
Searching...
No Matches
random_gen_value.h
1#ifndef RANDOM_GEN_VALUE_H
2#define RANDOM_GEN_VALUE_H
3
4#include <random>
5#include <stdexcept>
6#include <type_traits>
7
8template <typename RandType>
10 static_assert(std::is_arithmetic_v<RandType>, "RandType must be arithmetic");
11
12public:
13 static RandType random(const RandType min, const RandType max) {
14 if constexpr (std::is_integral_v<RandType>) {
15 static std::random_device rd;
16 static std::mt19937 gen(rd());
17 std::uniform_int_distribution<RandType> dis(min, max);
18 return dis(gen);
19 } else if constexpr (std::is_floating_point_v<RandType>) {
20 static std::random_device rd;
21 static std::mt19937 gen(rd());
22 std::uniform_real_distribution<RandType> dis(min, max);
23 return dis(gen);
24 } else {
25 throw std::logic_error("Unsupported type for RandomGenerator");
26 }
27 }
28
29 template <int MAX_TRY = 100>
30 static RandType random_except(const RandType min, const RandType max, const RandType except) {
31 if (min == max && min == except) {
32 throw std::logic_error("Cannot generate value: only one possible value which is excluded.");
33 }
34
35 for (int i = 0; i < MAX_TRY; ++i) {
36 RandType result = random(min, max);
37 if (result != except)
38 return result;
39 }
40
41 throw std::runtime_error("Too many attempts to generate a value different from 'except'");
42 }
43};
44
45#endif // RANDOM_GEN_VALUE_H
Definition random_gen_value.h:9