CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  1. #1
    Join Date
    Feb 2009
    Posts
    112

    Shuffling a deck of cards

    I'm having an issue tyring to write a program that will shuffle multiple decks of cards like at a casino. I have assigned each card an ID in an array, so:
    1 = 2 of dimonds
    2 = 2 of hearts
    3 = 2 of clubs
    .
    .
    .
    52 = Ace of spades

    What I'm doing is generating a random number between 1 and 52 and filling an array with the random number which will be the card ID. I have it do a for each loop to search the array to see if the random number chosen is already in there. If it is, it breaks the loop and tries again.

    There are no issues as far as errors are concerned, but it's incredibly inefficient. with 1 deck it doesn't long, but if there are 10 decks, the array size is 520 and it has to do the loop minimum 520 times. So it can take quite a bit of time to complete.

    Is there a more efficient way of doing this?

    Here is my code for shuffling:

    Code:
    private void ShuffleDeck()
            {
                CardOrder = new int[52];
    
                do
                {
                    Random RandomNumber = new Random();
                    int CardID = RandomNumber.Next(1, 53);
                    bool UsedCard = true;
    
                    foreach (int IDNumber in CardOrder)
                    {
                        if (CardID == IDNumber)
                        {
                            UsedCard = true;
                            break;
                        }
                        else
                        {
                            UsedCard = false;
                        }
                    }
                    if (UsedCard == false)
                    {
                        string cardcall = (CardListing[CardID - 1, 1]);
                        CardOrder[CardOrderIndex] = CardID;
                        listBox1.Items.Add((CardOrderIndex + 1).ToString() + ": " + CardListing[CardID - 1,1]);
                        CardOrderIndex++;
                    }
                }
                while (CardOrderIndex < 52);
                CardOrderIndex = 0;
            }
    Last edited by vandel212; February 5th, 2010 at 10:39 AM.
    - It's a long way to the top if you want to rock n' roll - AC/DC

    Check out my band and support the music:
    www.blueruinmusic.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured