I'm trying to shuffle the cards in a deck. I create two numbers randomly and assign their values to eachother 100 times. But it doesn't create randomly. Weirdest part is this, I put a breakpoint to line "counter++;" to observe if the program really chooses different cards each time. When I'm debugging, if I click on the continue button too quickly it creates same index1 and same index2 every time(but index1 is not equal to index2). I thought it may be due to the time. (when I click too quickly on the continue button or when I don't put breakpoint at all, it creates same numbers due to the same time.) But if that's the case, why does the program creates different values for index1 and index2? There is no breakpoint between their lines. So the time must be very small. It creates different indexes though. I'm confused. How to get rid of?
Edit: Solution is to use srand for one time, in main.
void mix(string *a){
srand(time(NULL));
if (finisher == 100){
return;
}
string b;
int pos1;
pos1 = rand() % 52;
b = a[pos1];
int pos2;
pos2 = rand() % 52;
cout << a[pos1] << " " << a[pos2] << endl; //These lines are only for testing
a[pos1] = a[pos2];
a[pos2] = b;
cout << a[pos1] << " " << a[pos2] << endl; //These lines are only for testing
counter++;
srand(time(NULL));
mix(a);
}
You are likely having a problem with the call to srand.
Your program runs the shuffle_cards function more than once within one second.
This means that the timestamp you feed to srand in srand(time(NULL));
is the same on more than one call.
Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
Thus both times the rand() call will generate the same index1 and index2 numbers as in the first call of the shuffle_cards function.
The solution is to not call srand or to call it once, for example when the program starts, or to call it less often.