CCIMXDesktop
 
Loading...
Searching...
No Matches
random_gen_value.h
1
6#ifndef RANDOM_GEN_VALUE_H
7#define RANDOM_GEN_VALUE_H
8
9#include <random> // For random number generation facilities (std::random_device, std::mt19937, distributions)
10#include <stdexcept> // For standard exception types (std::logic_error, std::runtime_error)
11#include <type_traits> // For type traits (std::is_arithmetic_v, std::is_integral_v, std::is_floating_point_v)
12
22template <typename RandType>
28 static_assert(std::is_arithmetic_v<RandType>, "RandType must be arithmetic");
29
30public:
42 static RandType random(const RandType min, const RandType max) {
43 if constexpr (std::is_integral_v<RandType>) {
44 // Static random_device and mt19937 ensure they are initialized only once across all calls.
45 static std::random_device rd;
46 static std::mt19937 gen(rd());
47 std::uniform_int_distribution<RandType> dis(min, max);
48 return dis(gen);
49 } else if constexpr (std::is_floating_point_v<RandType>) {
50 // Static random_device and mt19937 ensure they are initialized only once across all calls.
51 static std::random_device rd;
52 static std::mt19937 gen(rd());
53 std::uniform_real_distribution<RandType> dis(min, max);
54 return dis(gen);
55 } else {
56 // This branch should theoretically not be reached due to static_assert.
57 throw std::logic_error("Unsupported type for RandomGenerator");
58 }
59 }
60
74 template <int MAX_TRY = 100>
75 static RandType random_except(const RandType min, const RandType max, const RandType except) {
76 if (min == max && min == except) {
77 throw std::logic_error("Cannot generate value: only one possible value which is excluded.");
78 }
79
80 for (int i = 0; i < MAX_TRY; ++i) {
81 RandType result = random(min, max);
82 if (result != except)
83 return result;
84 }
85
86 throw std::runtime_error("Too many attempts to generate a value different from 'except'");
87 }
88};
89
90#endif // RANDOM_GEN_VALUE_H
A templated class for generating random numbers of a specified arithmetic type.
Definition random_gen_value.h:23
static RandType random_except(const RandType min, const RandType max, const RandType except)
Generates a random number within a specified range, excluding a particular value.
Definition random_gen_value.h:75
static RandType random(const RandType min, const RandType max)
Compile-time assertion to ensure RandType is an arithmetic type. If RandType is not arithmetic (e....
Definition random_gen_value.h:42