Georg
Georg

Reputation: 1098

C++ Random number generator apparent malfunction: am I unlucky?

I wanted to try the C++ random number generator but couldn't seem to obtain very satisfying results. For example here is an attempt among others to create a random string of characters.

#include <iostream>
#include <string>
#include <random>

std::string f(unsigned int n){
    std::uniform_int_distribution<int> dis025(0, 25);
    std::mt19937 gen_mt(n);
    std::string str(5, '\0');
    for(int i = 0; i<5; i++)
        str[i] = (char)('a' + dis025(gen_mt));
    return str;
}
int g(unsigned int n, int m){
    std::uniform_int_distribution<int> dis(0, m);
    std::mt19937 gen_mt(n);
    return dis(gen_mt);
}
int main() {
    std::string s = f(g(106175305, 40000000)) + " " + f(g(53718209, 40000000));
    std::cout << "Random string: " << s << std::endl;
}

Link to Coliru.

(I had to use the f(g()) trick so that it stops shouting insults.)
It is quite annoying and I doubt that is the desired behavior. But somehow I am helpless to prevent it, it keeps happening, again...

#include <iostream>
#include <string>
#include <random>

std::string fx(unsigned int n, int m){
    std::uniform_int_distribution<int> dis(0, m);
    std::mt19937 gen_mt(n);
    std::string str(6, '\0');
    for(int i = 0; i<6; i++)
        str[i] = (char)('.' + dis(gen_mt));
    return str;
}
int g(unsigned int n, int m){
    std::uniform_int_distribution<int> dis(0, m);
    std::mt19937 gen_mt(n);
    return dis(gen_mt);
}
int main() {
    std::string s1 = fx(g(66730461, 90000000) + 400000000, 33) + "/" + fx(g(28989020, 90000000) * 10, 43);
    std::cout << s1 << std::endl;
}

Coliru.
...and again.

int main() {
    std::string s2 = fx(g(66730461, 90000000) + 400000000, 33) + "/" + fx(g(81141643, 90000000) + 100000000, 43);
    std::cout << s2 << std::endl;
}

Do you often meet that kind of problem? or am I especially unlucky?

Upvotes: 0

Views: 197

Answers (1)

ContinuousLoad
ContinuousLoad

Reputation: 4922

My sad friend, I must inform you that in all my life I have never encountered a programmer with as poor luck as you have. The chances of a random string generator creating human-readable output is one in a million, but you managed to do it three times in a row (one in a trillion?)

In all honesty, the trick was quite clever. May your future endeavors be more predictable :)

(Future readers: The results were generated using hand-picked pseudo-random seed values that happened to output specific strings, like "hello world", etc... Check out the comments on the question for more info)

Upvotes: 3

Related Questions