rand()%10 generating the same number

Apr 21, 2013 at 6:06am
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.
Apr 21, 2013 at 6:12am
probably because you have rand()$10 instead of rand()%10 and you're probably getting a syn. error
Apr 21, 2013 at 6:45am
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/
Apr 21, 2013 at 8:30am
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 Apr 21, 2013 at 8:31am
Apr 21, 2013 at 9:54am
@ 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.