jeudi 26 octobre 2017

C++ random utility gets reinitialized, causing duplicated output

I have created a function within my utility namespace to generate a random number to prevent duplicate pieces of code. Unfortunately it not as random as it re initialize the variables each time it's called, so when i loop something it gets the same output from time(0) and so the same value.

As my experience is limited i don't know how to fix it, as a singleton can't being applied due to it not being a class.

#ifndef UTILS_INT_HEADER_INCLUDED
#define UTILS_INT_HEADER_INCLUDED

#include <iostream>
#include <random>
#include <ctime>

namespace utils
{
    static int random(int min, int max, int seed) {
        std::default_random_engine generator;
        generator.seed(seed);
        std::uniform_int_distribution<int> dist(min, max);
        return dist(generator);
    }

    static int random(int max) {
        return random(0, max, time(0));
    }

    static int random(int min, int max) {
        return random(min, max, time(0));
    }
}

#endif




Aucun commentaire:

Enregistrer un commentaire