pmt: add random number generator class (compile-time, with templates)

This commit is contained in:
2025-09-17 00:28:26 +03:00
parent 318739adc8
commit 7aca7792ae
2 changed files with 45 additions and 3 deletions

View File

@@ -71,11 +71,9 @@ RUN {
LOGN(MTFUN, INFO) << "Generating random data for testing" << std::endl;
auto *buffer = new (std::nothrow) char[bufferSize];
collector.delAfterProgress(buffer);
std::mt19937 rng(std::random_device{}());
std::uniform_int_distribution dist(0, 255);
for (size_t i = 0; i < bufferSize; i++)
buffer[i] = static_cast<char>(dist(rng));
buffer[i] = static_cast<char>(Helper::Random<1024>::getNumber());
collector.delFileAfterProgress(test);

View File

@@ -22,6 +22,8 @@
#include <exception>
#include <functional>
#include <optional>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
@@ -113,6 +115,48 @@ public:
void closeAfterProgress(int _fd);
};
template <int max = 100, int start = 0, int count = 10, int d = 0>
class Random {
static_assert(max > start, "max is larger than start");
static_assert(count > 1, "count is larger than 1");
static_assert(count <= max - start, "count is greater than max-start");
public:
static std::set<int> get() {
std::set<int> set;
std::random_device rd;
std::mt19937 gen(rd());
if constexpr (d > 0) {
std::uniform_int_distribution<> dist(0, (max - start - 1) / d);
while (set.size() < count)
set.insert(start + dist(gen) * d);
} else {
std::uniform_int_distribution<> dist(start, max - 1);
while (set.size() < count)
set.insert(dist(gen));
}
return set;
}
static int getNumber() {
std::random_device rd;
std::mt19937 gen(rd());
int ret;
if constexpr (d > 0) {
std::uniform_int_distribution<> dist(0, (max - start - 1) / d);
ret = start + dist(gen) * d;
} else {
std::uniform_int_distribution<> dist(start, max - 1); // max exclusive
ret = dist(gen);
}
return ret;
}
};
namespace LoggingProperties {
extern std::string_view FILE, NAME;
extern bool PRINT, DISABLE;