memgraph/include/utils/random/generator.h

76 lines
1.9 KiB
C
Raw Normal View History

2016-11-23 00:32:30 +08:00
#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> {
private:
int size_;
2016-11-23 00:32:30 +08:00
public:
StringGenerator(int size)
: RandomGenerator(std::uniform_int_distribution<int>(32, 126)),
size_(size) {}
2016-11-23 00:32:30 +08:00
std::string next(int size) {
std::string random_string;
random_string.reserve(size);
2016-11-23 00:32:30 +08:00
for (int i = 0; i < size; i++) random_string += (dist_(gen_) + '\0');
2016-11-23 00:32:30 +08:00
return random_string;
}
std::string next() { return next(size_); }
2016-11-23 00:32:30 +08:00
};
template <class Distribution, class Generator, class DistributionRangeType>
class NumberGenerator : public RandomGenerator<Distribution, Generator> {
2016-11-23 00:32:30 +08:00
public:
NumberGenerator(DistributionRangeType start, DistributionRangeType end)
: RandomGenerator<Distribution, Generator>(Distribution(start, end)) {}
2016-11-23 00:32:30 +08:00
auto next() { return this->dist_(this->gen_); }
2016-11-23 00:32:30 +08:00
};
template <class FirstGenerator, class SecondGenerator>
class PairGenerator {
private:
FirstGenerator *first_;
SecondGenerator *second_;
public:
PairGenerator(FirstGenerator *first, SecondGenerator *second)
: first_(first), second_(second) {}
auto next() { return std::make_pair(first_->next(), second_->next()); }
};
2016-11-23 00:32:30 +08:00
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();
2016-11-23 00:32:30 +08:00
return elements;
}
}; // namespace utils::random
}; // namespace ::utils