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++;
                }
            }
        }
    }
Abhijeet
  • 13,562
  • 26
  • 94
  • 175
  • You should check this [question](http://stackoverflow.com/questions/108819/best-way-to-randomize-a-string-array-with-net). – volkh4n Sep 15 '13 at 12:35
  • 5
    This seems kind of silly when there is a [simple O(n) shuffle algorithm](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). – Blastfurnace Sep 15 '13 at 13:07
  • 2
    [The Danger of Naïveté](http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html). – Hans Passant Sep 15 '13 at 14:03

1 Answers1

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.

Community
  • 1
  • 1
Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137