blitzeus
blitzeus

Reputation: 495

random_shuffle produces same results every time

Im trying to shuffle a deck of cards but random_shuffle produces the same result every time

void
Deck::shuffle() {

    cout << "SHUFFLING CARDS!!!\n\n";

    srand(time(0));
    random_shuffle(cards.begin(), cards.end());

    displayCards();
}

Upvotes: 1

Views: 2554

Answers (5)

Zac Howland
Zac Howland

Reputation: 15872

You are reseeding the random number generator each time you call shuffle.

You should only seed the random number generator once per application (typically in your application initialization):

int main()
{
    // other initialization
    srand(time(NULL)); // seed the number generator

    // ...
}

Upvotes: 1

P0W
P0W

Reputation: 47794

I'm not familiar with random_shuffle, but here's a function that does a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely.

This is from Gayle Laakmann's Cracking the Coding Interview (Question 20.2)

void Deck::shuffle() {

int temp, index;

for (int i = 0; i < cards.size(); i++){

    index = (int) (rand() %(cards.size() - i)) + i;

    temp = cards[i];
    cards[i] = cards[index];
    cards[index] = temp;

        }
}

Upvotes: 0

Hashman
Hashman

Reputation: 141

It is important to know that to be able to receive a "random" number you have to seed the generator. Also it should be seeded outside the function.

srand(time(NULL));

The use of the time function will help ensure that you will receive a random number.

time.h does need to be included for it to work. For more reference on srand, click here.

Upvotes: 0

Salvador Dali
Salvador Dali

Reputation: 222541

I think that the problem is because you are putting srand(...) inside of your function.

Try to move it outside (so that it will be executed only once)

Upvotes: 1

jrok
jrok

Reputation: 55395

That's because you seed pseudo-random number generator to the same value each time:

srand(time(0));

The granularity of time are seconds, if I'm not mistaken. If you pause the execution for some time between calls to Deck::shuffle() you should see different results.

Remove that line from the function and call it once at the start of your program.

Upvotes: 5

Related Questions