I am trying to write a code for a project that lists the contents of a deck of cards, asks how much times the person wants to shuffle the deck, and then shuffles them. It has to use a method to create two random integers using the System.Random class.
These are my classes:
Program.cs:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Deck mydeck = new Deck();
foreach (Card c in mydeck.Cards)
{
Console.WriteLine(c);
}
Console.WriteLine("How Many Times Do You Want To Shuffle?");
}
}
}
Deck.cs:
namespace ConsoleApplication1
{
class Deck
{
Card[] cards = new Card[52];
string[] numbers = new string[] { "2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K" };
public Deck()
{
int i = 0;
foreach(string s in numbers)
{
cards[i] = new Card(Suits.Clubs, s);
i++;
}
foreach (string s in numbers)
{
cards[i] = new Card(Suits.Spades, s);
i++;
}
foreach (string s in numbers)
{
cards[i] = new Card(Suits.Hearts, s);
i++;
}
foreach (string s in numbers)
{
cards[i] = new Card(Suits.Diamonds, s);
i++;
}
}
public Card[] Cards
{
get
{
return cards;
}
}
}
}
Enums.cs:
namespace ConsoleApplication1
{
enum Suits
{
Hearts,
Diamonds,
Spades,
Clubs
}
}
Card.cs:
namespace ConsoleApplication1
{
class Card
{
protected Suits suit;
protected string cardvalue;
public Card()
{
}
public Card(Suits suit2, string cardvalue2)
{
suit = suit2;
cardvalue = cardvalue2;
}
public override string ToString()
{
return string.Format("{0} of {1}", cardvalue, suit);
}
}
}
Please tell me how to make the cards shuffle as much as the person wants and then list the shuffled cards.
The shuffling should work in this manner:
You take two random cards in the deck (the index of the card in the deck is the random numbers) And swap positions of the two cards. For instance take card at index 2 and card at index 9 and have them change place.
And that can be repeated a certain number of times.
The algorithm should look something like this:
Your Shuffle might work, but it's not really efficient and not lifelike. You should try this way:
This way you might get a more lifelike shuffle with less iterations
Shuffling a deck of cards is something that seems trivial at first, but usually the algorithm that most people come up with is incorrect.
Jeff Atwood (Coding Horror) wrote a few very good articles on the subject:
http://www.codinghorror.com/blog/archives/001008.html
http://www.codinghorror.com/blog/archives/001015.html
(especially the second one is a must-read)