在C#中洗牌 [英] Card Shuffling in C#
本文介绍了在C#中洗牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图写一个$ C $下一个项目,列出一副扑克牌的内容,问的人有多少次都想洗牌,然后打乱它们。它必须使用一种方法来创建使用System.Random类两个随机整数。
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.
这些都是我的课:
Program.cs的:
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:
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:
Enums.cs:
namespace ConsoleApplication1
{
enum Suits
{
Hearts,
Diamonds,
Spades,
Clubs
}
}
Card.cs:
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.
推荐答案
使用费雪耶茨洗牌。
您的C#code应该是这个样子:
Your C# code should look something like this:
static public class FisherYates
{
static Random r = new Random();
// Based on Java code from wikipedia:
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
static public void Shuffle(int[] deck)
{
for (int n = deck.Length - 1; n > 0; --n)
{
int k = r.Next(n+1);
int temp = deck[n];
deck[n] = deck[k];
deck[k] = temp;
}
}
}
这篇关于在C#中洗牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文