Reputation: 289
I'm trying to shuffle a deck of cards by randomly taking cards from one deck, and putting them into the other, to avoid getting duplicates of the cards once they are added to the new list they are removed from the original list, this seems to be causing the argument out of range error, despite my efforts to de-increment the range of the random number. Suggestions please?
List<Card> shuffledDeck = new List<Card> ();
for (int i = 0; i <= 51; ++i)
{
int c = myDeck.Count + 1;
int n = rNumber.Next (1, c);
shuffledDeck.Add(myDeck[n]);
myDeck.Remove(myDeck[n]);
}
Upvotes: 3
Views: 120
Reputation: 4363
List<Card> shuffledDeck = new List<Card> ();
while (myDeck.Count > 0)
{
int c = myDeck.Count;
int n = rNumber.Next (0, c);
var value = myDeck[n];
shuffledDeck.Add(value);
myDeck.Remove(value);
}
You need to make sure you don't have an index more than actual array objects count.
Upvotes: 2