From 5864e5abc43b201c3801fa39a2fcaf9e3a9e8914 Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 27 Feb 2022 12:54:10 +0100 Subject: refactor: use dependency injection --- src/randomization/generator.cpp | 14 ++++++++++++++ src/randomization/generator.hpp | 18 ++++++++++++++++++ src/randomization/seed_generator.cpp | 11 +++++++++++ src/randomization/seed_generator.hpp | 17 +++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 src/randomization/generator.cpp create mode 100644 src/randomization/generator.hpp create mode 100644 src/randomization/seed_generator.cpp create mode 100644 src/randomization/seed_generator.hpp (limited to 'src/randomization') diff --git a/src/randomization/generator.cpp b/src/randomization/generator.cpp new file mode 100644 index 0000000..b9bcb8a --- /dev/null +++ b/src/randomization/generator.cpp @@ -0,0 +1,14 @@ +#include "generator.hpp" + +RandomNumberGenerator::RandomNumberGenerator(const unsigned int &seed) +{ + this->_generator = std::make_unique(seed); +} + +unsigned int RandomNumberGenerator::in_range(const unsigned int &a, + const unsigned int &b) const +{ + auto random_distribution = std::uniform_int_distribution(a, b); + + return random_distribution(*this->_generator); +} diff --git a/src/randomization/generator.hpp b/src/randomization/generator.hpp new file mode 100644 index 0000000..3acfc98 --- /dev/null +++ b/src/randomization/generator.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include "interfaces/randomization.hpp" + +#include +#include + +class RandomNumberGenerator : public IRandomNumberGenerator +{ +public: + explicit RandomNumberGenerator(const unsigned int &seed); + + [[nodiscard]] unsigned int in_range(const unsigned int &a, + const unsigned int &b) const override; + +private: + std::unique_ptr _generator; +}; diff --git a/src/randomization/seed_generator.cpp b/src/randomization/seed_generator.cpp new file mode 100644 index 0000000..fdb2b12 --- /dev/null +++ b/src/randomization/seed_generator.cpp @@ -0,0 +1,11 @@ +#include "seed_generator.hpp" + +SeedGenerator::SeedGenerator(const std::shared_ptr &random_device) + : _random_device(random_device) +{ +} + +unsigned int SeedGenerator::random_seed() const +{ + return (*_random_device)(); +} diff --git a/src/randomization/seed_generator.hpp b/src/randomization/seed_generator.hpp new file mode 100644 index 0000000..238fdbe --- /dev/null +++ b/src/randomization/seed_generator.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "interfaces/randomization.hpp" + +#include +#include + +class SeedGenerator : public ISeedGenerator +{ +public: + explicit SeedGenerator(const std::shared_ptr &random_device); + + [[nodiscard]] unsigned int random_seed() const override; + +private: + const std::shared_ptr &_random_device; +}; -- cgit v1.2.3-18-g5258