From d0a9401a54212533be1ee752d87f5ee023c2dbb6 Mon Sep 17 00:00:00 2001 From: niansa Date: Fri, 27 Oct 2023 08:41:27 +0200 Subject: [PATCH] Added RandomGenerator class --- CMakeLists.txt | 3 ++- include/commoncpp/random.hpp | 47 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 include/commoncpp/random.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c07ee92..9052a9d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,7 +11,8 @@ add_library(commoncpp STATIC config.cpp include/commoncpp/config.hpp utils.cpp include/commoncpp/utils.hpp pooled_thread.cpp include/commoncpp/pooled_thread.hpp - include/commoncpp/timer.hpp) + include/commoncpp/timer.hpp + include/commoncpp/random.hpp) target_include_directories(commoncpp PUBLIC include/) target_include_directories(commoncpp PRIVATE include/commoncpp/) diff --git a/include/commoncpp/random.hpp b/include/commoncpp/random.hpp new file mode 100644 index 0000000..ad23dd8 --- /dev/null +++ b/include/commoncpp/random.hpp @@ -0,0 +1,47 @@ +#ifndef RANDOM_HPP +#define RANDOM_HPP +#include + + + +namespace common { +class RandomGenerator { + std::mt19937 rng; + uint32_t initialSeed; + +public: +#ifndef COMMONCPP_LITE + void seed() { + rng.seed(initialSeed = std::random_device{}()); + } +#endif + void seed(uint32_t customSeed) { + rng.seed(initialSeed = customSeed); + } + + unsigned getUInt() { + std::uniform_int_distribution dist; + return dist(rng); + } + unsigned getUInt(unsigned max) { + std::uniform_int_distribution dist(0, max); + return dist(rng); + } + unsigned getUInt(unsigned min, unsigned max) { + std::uniform_int_distribution dist(min, max); + return dist(rng); + } + double getDouble(double max) { + std::uniform_real_distribution dist(0.0, max); + return dist(rng); + } + double getDouble(double min, double max) { + std::uniform_real_distribution dist(min, max); + return dist(rng); + } + bool getBool(float chance) { + return getDouble(1.0) <= chance && chance != 0.0f; + } +}; +} +#endif // RANDOM_HPP