Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

srand(n) giving same values for any n

void generator() 
{
    int n = <some number>;
    srand(n);
    int first = randint(9);
    digits.push_back(first);
    while (digits.size() < 4) 
    {
        bool flag = true;
        int num = randint(9);
        for (int j = 0; j < digits.size(); j++) 
        {
            if (num == digits[j]) 
            {
                flag = false;
                break;
            }
        }
        if (flag == true) 
        {
            digits.push_back(num);
        }
    }
    for (int i : digits)
    {
        cout << i << " ";
    }
}

int main() 
{
 generator();
}

This code is supposed to generate 4 random and distinct digits on execution.

randint(x) is a function which generates a single random value anywhere between 0 and x.

While my digits are distinct, they aren’t random. No matter what value I put inside srand(), I’m getting the same four digits:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2 4 5 1

Help me out if I’m doing something wrong.

>Solution :

std::experimental::randint is coupled with std::experimental::reseed to set the seed per thread: srand will have no effect on the generated output. You’ll probably find that randint is automatically seeded with a constant value which accounts for your output. As it never became part of the C++ standard, I cannot comment further with certainty.

This is all non-standard, all non-portable, and best avoided from C++11 now we have <random>.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading