0

I am trying to have a "deck" of cards get "shuffled" randomly, but can't seem to figure out why I get a list of the same random number 52 times. The randomizer works for the first iteration but then the same random number gets inserted into the array for the following 51 cards.

//Shuffle Cards
    int cardsArray[52] = { 0 };
    bool repeatedValue = false;

    for (int k = 0; k < 52; k++)
    {
        srand(time(NULL));
        int i;
        i = (rand() % 52) + 0;

        for (int j = 0; j < 52; j++)
        {
            if (i == cardsArray[j])
            {
                repeatedValue = true;
            }
        }

        if (repeatedValue == true)
        {
            continue;
        }

        cardsArray[k] = i;
    }
  • 2
    Since time passes relatively slowly if you are a computer, you are seeding the random number generator with the same value every time round the loop. As a result, you generate the same (non-) random number each time through. To fix this, move the call to `srand` above the `for` loop. – Paul Sanders Jun 02 '20 at 00:16
  • **WARNING**: Using [`rand()` can be highly problematic](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) and you’re strongly encouraged to use an appropriate [random number generator facility in the Standard Library](http://en.cppreference.com/w/cpp/numeric/random) that produces high-quality random values. Your use of `time(NULL)` as a random number seed means that this will produce identical results if run in the same second, and on many platforms `rand()` is [*barely* random at all](http://dilbert.com/strip/2001-10-25). – tadman Jun 02 '20 at 01:41
  • @tadman: the problem with rand() are the least of OP's issues if they keep seeding the PRNG in a loop. – Jeffrey Jun 02 '20 at 02:01
  • @Jeffrey True, but debugging `rand()`-based code is kind of a miss considering C++ can do so much better. – tadman Jun 02 '20 at 02:11

0 Answers0