vendredi 29 juin 2018

Fast random string

I'm trying to generate random string ID for a program (the ID has to be unique only during the execution of the program). I first did it in Python without any issue :

class RandomIdGenerator:
    _base_62_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    @classmethod
    def get_base_62(cls, length):
        return "".join([random.choice(RandomIdGenerator._base_62_chars) for _ in range(length)])

But as I need my program to be in C++, I'm trying to generate the same string with it. This is what I do now :

void Node::setId()
{
    QString allow_symbols("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    qsrand(QTime::currentTime().msec());

    for (int i = 0; i < ID_LENGTH; ++i) {
        id_.append(allow_symbols.at(qrand() % (allow_symbols.length())));
    }
}

I have two main issues with it. First it doesn't use C++11 (I don't know how Qt works but I don't think it's C++11) and the ID generated are all the same. If I generate four of them I get :

"R4NDM1xM"
"R4NDM1xM"
"R4NDM1xM"
"R4NDM1xM"

I tried using the C++11 method but I got the same result, even worse, at each execution, I got the exact same result :

void Node::setId()
{
    id_ = "";

    const std::string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    std::random_device rd;
    std::mt19937 generator(rd);
    std::uniform_int_distribution<int> dist(0, str.size() - 1);

    for (int i = 0; i < Node::ID_LENGTH; ++i)
        id_ += str[dist(generator)];
}

How can I generate random string ID at each call of a method?

Aucun commentaire:

Enregistrer un commentaire