Solved

Method List explanation on a sort

Posted on 2013-10-23
2
216 Views
Last Modified: 2013-10-24
I have the following code and I'm trying to understand the Shuffle() method from the Deck class... It will be nice to get an explanation  from line by line of the suffle method line by line.

public void Shuffle()
        {
            Random rand = new Random();
            for (int i = cards.Count - 1; i > 0; i--)
            {
                int randomIndexg = rand.Next(i + 1);
                Card tempCard = cards[i];
                cards[i] = cards[randomIndexg];
                cards[randomIndexg] = tempCard;
            }
        }

Open in new window


Class Deck
 public class Deck
    {
        #region Fields

        List<Card> cards = new List<Card>();

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        public Deck()
        {
            // fill the deck with cards
            foreach (Suit suit in Enum.GetValues(typeof(Suit)))
            {
                foreach (Rank rank in Enum.GetValues(typeof(Rank)))
                {
                    cards.Add(new Card(rank.ToString(), suit.ToString()));
                }
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets whether the deck is empty
        /// </summary>
        public bool Empty
        {
            get { return cards.Count == 0; }
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Cuts the deck of cards at the given location
        /// </summary>
        /// <param name="location">the location at which to cut the deck</param>
        public void Cut(int location)
        {
            //int cutIndex = cards.Count - location;
            //List<Card> newCards = new List<Card>(cards.Count);
            //for (int i = cutIndex; i < cards.Count; i++)
            //{
            //    newCards.Add(cards[i]);
            //}
            //for (int i = 0; i < cutIndex; i++)
            //{
            //    newCards.Add(cards[i]);
            //}
            //cards = newCards;

            int cutIndex = cards.Count - location;
            Card[] newCards = new Card[cards.Count];
            cards.CopyTo(cutIndex, newCards, 0, location);
            cards.CopyTo(0, newCards, location, cutIndex);
            cards.Clear();
            cards.InsertRange(0, newCards);
        }

        /// <summary>
        /// Shuffles the deck
        /// 
        /// Reference: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#shuffle%28java.util.List%29
        /// </summary>
        public void Shuffle()
        {
            Random rand = new Random();
            for (int i = cards.Count - 1; i > 0; i--)
            {
                int randomIndex = rand.Next(i + 1);
                Card tempCard = cards[i];
                cards[i] = cards[randomIndex];
                cards[randomIndex] = tempCard;
            }
        }

        /// <summary>
        /// Takes the top card from the deck. If the deck is empty, returns null
        /// </summary>
        /// <returns>the top card</returns>
        public Card TakeTopCard()
        {
            if (!Empty)
            {
                Card topCard = cards[cards.Count - 1];
                cards.RemoveAt(cards.Count - 1);
                return topCard;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Prints the contents of the deck
        /// </summary>
        public void Print()
        {
            foreach (Card card in cards)
            {
                Console.WriteLine(card.Rank + " of " + card.Suit);
            }
        }
        #endregion
    }

Open in new window

0
Comment
Question by:yguyon28
2 Comments
 

Author Comment

by:yguyon28
ID: 39595401
public void Shuffle()
        {
            Random rand = new Random();
            for (int i = cards.Count - 1; i > 0; i--)
            {
                int randomIndexg = rand.Next(i + 1);
                Card tempCard = cards[i];
                cards[i] = cards[randomIndexg];
                cards[randomIndexg] = tempCard;
            }
        }

Open in new window

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 39595504
public void Shuffle()
{
    Random rand = new Random();                 // Create a new Random object. This will be used to create pseudo-random numbers.
    for (int i = cards.Count - 1; i > 0; i--)   // Create a loop to loop over deck. The loop will iterate cards.Count - 1 times.
    {
        int randomIndexg = rand.Next(i + 1);    // Get the next random integer less than i + 1 and greater than or equal to zero.
        Card tempCard = cards[i];               // Create a temporary variable that points to the Card object located at slot i of the cards List.
        cards[i] = cards[randomIndexg];         // Set slot i of the cards list to point to the Card object at slot randomIndexg of the cards List.
        cards[randomIndexg] = tempCard;         // Set slot randomIndexg of the cards list to point to the Card object that the temporary variable is point to
    }
}

// The net effect is that two cards swap positions. The positions swapped are i and randomIndexg

Open in new window

0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.Net How to Exit Sub - Exit Form??? 5 57
Export import database 4 51
Device Location 4 29
How can i use linq for parsing string datetime to real datetime? 16 44
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now