1

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;
}
  1. I have added a variable randomOrder with each card.
  2. Then I am using Randome.Next() to get a random number for each card.
  3. 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++;
                }
            }
        }
    }
4

1 回答 1

2

You can replace the whole body of the ShuffleDeck method with

return deck.OrderBy(d => r.Next());

This probably doesn't affect the algorithmic complexity, but it makes the method simpler.

Update:

My opinion is that thinking in terms of Big-O notation is not relevant here unless you have to shuffle millions of decks and discover that performance is really a problem.

于 2013-09-15T12:27:49.893 回答