dimanche 5 mars 2017

How do I Ensure a unique random number are produced for an array of int?

I am writing a deal function for a Card class. I only have one suit to deal from. The number of cards dealt can be from five to ten. The method I came up with still will potentially produce a duplicate randomly (about 20% of the time when the number of cards dealt I select to be the max which is 10). Just looking at the method I didn’t think a duplicate would be possible. Other than pointing out that rand() is not a true random number generator, would any of you care to point me to my mistake or mistakes?

for (int i = 0; i < noCards; i++)
{
    hand[i] = (rand() % 13) + 2;

    for (int j = 0; j < i; j++)
    {
        if (hand[i] == hand[j])
        {
            hand[i] = (rand() % 13) + 2;
            j = 0; // Restart the inner loop
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire