Sinan Samet Sinan Samet -4 years ago 97
C# Question

Shuffling different decks give the same deck for both?

I have this shuffling method in the

Deck
class:

public Card[] deck = new Card[DECK_AMOUNT];
public void shuffleCards()
{
Random randInt = new Random();

for (int i = 0; i < 52; i++)
{
int firstCard = i;
int secondCard = randInt.Next(0, 51);

int tempFirstCard = firstCard;

deck[i] = deck[secondCard];
deck[secondCard] = deck[i];

}
}


And when I make these properties:

private Deck computerCards;
private Deck playerCards;


And use these methods

private void shuffleDecks(){
computerCards.shuffleCards();
playerCards.shuffleCards();
}


They both have the same cards on the same positions. Why does this happen and how do I solve it?

If I were to do

private void shuffleDecks(){
computerCards.shuffleCards();
playerCards.shuffleCards();
playerCards.shuffleCards();
}


They are both different.

Answer Source

From the manual:

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers. You can also work around it by modifying the seed value returned by the system clock and then explicitly providing this new seed value to the Random(Int32) constructor. For more information, see the Random(Int32) constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download