samedi 19 mars 2022

Why does my functions generate always the same "randomness"? [duplicate]

I thought that the shuffle_string function would have generated a new seed each time gets called (so every time the cycle repeats), but something is wrong.

What could I do to circumvent this problem?

(COMPILER: g++, OS: Windows 10 x64)

Edit: Compiling with Visual Studio my code is actually running as expected.

Edit2: As suggest in the comments by @Eljay , adding 'static' before

std::random_device rd;

and before

std::mt19937_64 mt64{ rd() };

makes my program run fine even if comping with g++.

#include <iostream>
#include <random>

using std::cin; using std::cout;

void shuffle_string(std::string& s) {
    auto size = s.size();
    std::random_device rd;
    std::mt19937_64 mt64{ rd() };
    std::uniform_int_distribution<unsigned long long int> ind_range (0, size-1);
    for (auto i = 0; i < size; ++i) {
        std::swap(s[i], s[ind_range(mt64)]);
    }
}
int main() {
    while (true) {
    std::string string;
    cout << "Enter the string you want to randomly shuffle:\n";
    std::getline(cin, string);
    if (string == "exit") { return 0; }

    shuffle_string(string);

    cout << string << '\n';
    }
}

P.S.: I know i should always prefer std::shuffle, but i'm writing this only with the aim of learn something new (and actually this problem is something new).

Thanks, good evening.




Aucun commentaire:

Enregistrer un commentaire