I’m attempting to shuffle a deck of cards using the rand() function but for some reason when I try to see what the shuffled deck looks like, it comes out completely unshuffled. I’m not sure what I’m missing so any help would be greatly appreciated.
void Deck::Shuffle()
{
for (int j = 0; j <= 51; j++)
{
srand(time(0));
int i = 1 + rand()%52;
int k = 1 + rand()%52;
Card temp = theDeck[i];
theDeck[i] = theDeck[k];
theDeck[k]= temp;
}
}
Edit: Thank you for your help everyone. I’ve fixed the code to now read.
void Deck::Shuffle()
{
srand(time(0));
for (int j = 0; j <= 51; j++)
{
int i = 1 + rand()%52;
int k = 1 + rand()%52;
Card temp = theDeck[i];
theDeck[i] = theDeck[k];
theDeck[k]= temp;
}
}
srandshould only be called once per program execution, not every time you callrand. Your loop is running so fast, due to the speed of computers nowadays, that you are probably getting the same random number every single time, because you keep resetting the random number generator using the same seed (the time, which probably doesn’t change at all through your execution). Fix that.Update:
Your fix is better, but even better would be this: