Added basic random utility
This commit is contained in:
parent
bbd6f91e5f
commit
5a8a7bea65
76
include/utils/random/generator.h
Normal file
76
include/utils/random/generator.h
Normal file
@ -0,0 +1,76 @@
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
// namespace ::utils
|
||||
namespace utils {
|
||||
|
||||
// namespace utils::random
|
||||
namespace random {
|
||||
|
||||
template <class Distribution, class Generator>
|
||||
class RandomGenerator {
|
||||
private:
|
||||
std::random_device device_;
|
||||
|
||||
protected:
|
||||
Generator gen_;
|
||||
Distribution dist_;
|
||||
|
||||
public:
|
||||
RandomGenerator(Distribution dist) : gen_(device_()), dist_(dist) {}
|
||||
|
||||
};
|
||||
|
||||
class StringGenerator
|
||||
: public RandomGenerator<std::uniform_int_distribution<int>,
|
||||
std::default_random_engine> {
|
||||
public:
|
||||
StringGenerator()
|
||||
: RandomGenerator(std::uniform_int_distribution<int>(32, 126)) {}
|
||||
|
||||
std::string next(int size) {
|
||||
std::string random_string;
|
||||
|
||||
for (int i = 0; i < size; i++) random_string += (dist_(gen_) + '\0');
|
||||
return random_string;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
template <class Distribution, class Generator, class DistributionRangeType>
|
||||
class IntegerGenerator : public RandomGenerator<Distribution, Generator> {
|
||||
|
||||
public:
|
||||
IntegerGenerator(DistributionRangeType start, DistributionRangeType end) :
|
||||
RandomGenerator<Distribution,Generator>(Distribution(start, end)){}
|
||||
|
||||
int next() {
|
||||
return this->dist_(this->gen_);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
template <class Distribution, class Generator, class DistributionRangeType>
|
||||
class DecimalGenerator : public RandomGenerator<Distribution, Generator> {
|
||||
|
||||
public:
|
||||
DecimalGenerator(DistributionRangeType start, DistributionRangeType end) :
|
||||
RandomGenerator<Distribution, Generator>(Distribution(start, end)) {}
|
||||
|
||||
auto next() {
|
||||
return this->dist_(this->gen_);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
template <class RandomGenerator>
|
||||
auto generate_vector(RandomGenerator& gen, int size) {
|
||||
std::vector<decltype (gen.next())> elements(size);
|
||||
for (int i = 0; i < size; i++)
|
||||
elements[i] = gen.next();
|
||||
return elements;
|
||||
}
|
||||
|
||||
}; // namespace utils::random
|
||||
}; // namespace ::utils
|
Loading…
Reference in New Issue
Block a user