rand()%10 generating the same number

hi i assign rand()%50 to

1
2
3
4
5
operands[2];

operands[0] = rand()%50;
operands[1] = rand()%50;


i use it for one problem but down the road i re assgn both to

1
2
operands[2] = {rand()$10, rand()%10};


for another problem and it generates the same 2 numbers from the first question any help aprriciated thank you.
probably because you have rand()$10 instead of rand()%10 and you're probably getting a syn. error
Do you seed your random number generator? Do it once in the program, preferably in main().

1
2
3
4
5
6
#include <cstdlib>
#include <ctime>

// ...

std::srand(std::time(NULL));


http://cplusplus.com/reference/cstdlib/srand/
For your first case, you actually still have a 2% probability that the numbers will be the same. For the second case, you have a 10% probability that the numbers will be the same. That's why you are noticing the second case giving two of the same number.

If you want to ensure that the two numbers are difference, try one of these:
1
2
3
4
5
6
7
8
int operands[2];
operands[0] = rand()%10;
operands[1] = rand()%10;

while(operands[1] == operands[0])
{
    operands[1] = rand()%10;
}


Or
1
2
3
4
5
6
7
8
9
10
11
std::vector<int> temp;

// there is a std:: function for this, but I can't find it
for (int i = 0; i < 10; ++i)
    temp.push_back(i);

std::random_shuffle(temp.begin(), temp.end());

int operands[2];
operands[0] = temp[0];
operands[1] = temp[1];


The second option may appear to be slower than the first option (and usually is), but the first option has the potential to go on forever. It is the uncertainty in the first option that makes me prefer the second option.
Last edited on
@ Stewbond: you probably mean C++11's std::iota(), which does not yet appear in this site's Reference:

http://en.cppreference.com/w/cpp/algorithm/iota
Topic archived. No new replies allowed.