C++11 custom uniform integer distribution implementation

97 views Asked by At

I write code in C++ that need to be cross-platform. I need a uniform integer pseudo-random number generator to give the same results on different platforms (not cryptographic strength). As I understand from posts the existing std::uniform_int_distribution is implementation dependent. I was not able to find an existing integral numbers implementation, the closest I found was real numbers implementation: C++11 random number distributions are not consistent across platforms -- what alternatives are there?. So I wrote my own simple implementation:

template <typename T = int>
class SimpleIntDistribution
{
public:
    typedef T result_type;

public:
    SimpleIntDistribution(T a = {}, T b = {}) :
        _a{ a }, _b{ b } {}

    void reset() {}

    template <class Gen>
    T operator()(Gen& g)
    {
        using gen_res_type = typename Gen::result_type;
        // number of elements in distribution range
        gen_res_type distRange = static_cast<gen_res_type>(
            _b - _a + static_cast<T>(1));
        // normalized generator value
        gen_res_type normGenValue = g() - g.min();
        return _a + normGenValue % distRange;
    }

    T a() const { return _a; }
    T b() const { return _b; }

protected:
    T _a;
    T _b;
};

class Rand_int
{
public:
    Rand_int(int low, int high) : dist{ low, high } {}
    int operator()() { return dist(re); }
    void seed(int s) { re.seed(s); }

private:
    // std::default_random_engine re;
    std::mt19937 re;
    // std::uniform_int_distribution<> dist;
    SimpleIntDistribution<> dist;
};

int main()
{
    Rand_int r{ -10, 10 };
    r.seed(100);
    for (size_t i = 0; i < 20; i++)
    {
        int val = r();
        std::cout << val << ", ";
    }
}

I would be happy to receive comments on this code to understand potential pitfalls. Another option, if anybody could point to a better simple implementation code (not existing heavy libraries like boost, etc.)

0

There are 0 answers