Using framework's Random
class I came up with following lazy implementation to shuffle a deck of card.
I estimate worst case complexity of following code as O(N + NlogN). Am I right?
DataStructures
enum SuitType
{
Diamond,
Heart,
Spade,
Club
}
class Card
{
public SuitType suitType;
public int value;
public int randomOrder;
}
- I have added a variable randomOrder with each card.
- Then I am using Randome.Next() to get a random number for each card.
- Sort the deck based on this random number.
class Program
{
static void Main(string[] args)
{
Program p = new Program();
List<Card> deck = new List<Card>(52);
p.InitializeDeck(deck);
List<Card> shuffledDeck = p.ShuffleDeck(deck).ToList();
}
Random r = new Random();
readonly int RMIN = 1, RMAX = 100;
//O(N + NlogN)
private IEnumerable<Card> ShuffleDeck(List<Card> deck)
{
//O(N)
foreach (var d in deck)
{
d.randomOrder = r.Next(RMIN, RMAX);
}
//O(NlogN)
return deck.OrderBy(d => d.randomOrder);
}
private void InitializeDeck(List<Card> deck)
{
int suitCounter = 0;
for (int i = 1; i <= 52; i++)
{
deck.Add(new Card
{
suitType = (SuitType)suitCounter,
value = i,
randomOrder = r.Next(RMIN, RMAX)
});
if (i % 13 == 0)
{
suitCounter++;
}
}
}
}