用C#實現撲克牌排序

姚琪琳發表於2012-11-30

看到各大語言都有了,怎麼能沒有C#?

思路:同樣是給牌賦權重,轉換成對權重的排序。用最簡單的氣泡排序實現。另外不用轉換成權重也是很簡單的,可以先對花色進行分組,對每個組進行排序,再對分組的key進行排序。

優點:用C#實現的話,至少可以顯得OO一點。另外排序演算法是與具體物件無關的,是個通用的演算法。

先定義Card類,以及相關列舉:

class Card
{
    public CardSuit Suit { get; private set; }
    public CardValue Value { get; private set; }
    public int Weight { get { return (int)Suit * (int)Value; } }
    Card(CardSuit suit, CardValue value)
    {
        Suit = suit;
        Value = value;
    }
    public static Card Of(CardSuit suit, CardValue value)
    {
        return new Card(suit, value);
    }
    public override string ToString()
    {
        return Suit.ToString() + Value.ToString();
    }
}

enum CardSuit
{
    Spade = 1, Heart = 10, Club = 100, Diamond = 1000
}

enum CardValue
{ 
    Tow = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10, Jack = 11, Queen = 12, King = 13, Ace = 14
}

與具體物件無關的氣泡排序:

static TSource[] BubbleSort<TSource, TKey>(TSource[] elements, Func<TSource, TKey> keySelector)
{
    TSource tempElement;
    Comparer<TKey> comparer = Comparer<TKey>.Default;
    int j = elements.Length;
    while (j > 0)
    {
        for (int i = 0; i < j -1; i++)
        {
            if (comparer.Compare(keySelector(elements[i]), keySelector(elements[i + 1])) > 0)
            {
                tempElement = elements[i];
                elements[i] = elements[i + 1];
                elements[i + 1] = tempElement;
            }
        }
        j--;
    }
    return elements;
}  

獲取亂序撲克的演算法要複雜得多了,這個前兩天左耳朵耗子討論過。不過由於題目中規定亂序撲克是給定的條件,所以就無需擔心這一點了。其餘程式碼如下:

static void Main(string[] args)
{
    var cards = SortedCard();
    foreach (var card in cards)
    {
        Console.WriteLine(card);
    }
    Console.ReadLine();
}

static Card[] SortedCard()
{
    var cards = GetCards();
    return BubbleSort(cards, card => card.Weight);
}

static Card[] GetCards()
{
    var cards = new Card[] { Card.Of(CardSuit.Club, CardValue.Seven), 
                                Card.Of(CardSuit.Heart, CardValue.Jack),
                                Card.Of(CardSuit.Spade, CardValue.Ace),
                                Card.Of(CardSuit.Heart, CardValue.Tow),
                                Card.Of(CardSuit.Club, CardValue.King),
                                Card.Of(CardSuit.Diamond, CardValue.Ace),
                                Card.Of(CardSuit.Diamond, CardValue.Five),
                                Card.Of(CardSuit.Spade, CardValue.Nine),
                                // other cards...
    };
    return cards;
} 

相關文章