random_shuffle produces same results every time

落花浮王杯 提交于 2019-12-08 03:54:26

问题


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();
}

回答1:


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.




回答2:


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)




回答3:


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

    // ...
}



回答4:


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.




回答5:


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;

        }
}


来源:https://stackoverflow.com/questions/18278656/random-shuffle-produces-same-results-every-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!