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:
2 4 5 1
Help me out if I'm doing something wrong.
CodePudding user response:
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>
.