計算機科学のブログ

enums and collections - Organizing your data - Sort, IComparer, Compare method

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 8(enums and collections - Organizing your data)、p.433(Exercise)の解答を求めてみる。

コード

CardComparerByValue.cs

using System;
using System.Collections.Generic;

namespace MyFirstConsoleApp
{
    public class CardComparerByValue: IComparer<Card>
    {
        public CardComparerByValue()
        {
        }

        public int Compare(Card x, Card y)
        {
            if (x.Suit < y.Suit)
            {
                return -1;
            }
            if (x.Suit > y.Suit)
            {
                return 1;
            }
            if (x.Value < y.Value)
            {
                return -1;
            }
            if (x.Value > y.Value)
            {
                return 1;
            }
            return 0;
        }
    }
}

コード

Program.cs

using System;
using System.Collections.Generic;

namespace MyFirstConsoleApp
{
    class Program
    {
        static Random random = new Random();
        static Card RandomCard()
        {
            return new Card(
                (Values)random.Next(1, 14),
                (Suits)random.Next(4));
        }
        static void PrintCards(List<Card> cards)
        {
            foreach (var card in cards)
            {
                Console.WriteLine(card.Name);
            }
        }
        static void Main(string[] args)
        {
            Console.Write("Enter number of cards: ");
            string s = Console.ReadLine();
            if (int.TryParse(s, out int num))
            {
                List<Card> cards = new List<Card>();
                for (int i = 0; i < num; i++)
                {
                    cards.Add(RandomCard());
                }
                PrintCards(cards);
                Console.WriteLine("\n... sorting the cards ...\n");
                cards.Sort(new CardComparerByValue());
                PrintCards(cards);
            }
        }
    }
}

入出力結果(Terminal, Zsh)

Enter number of cards: 20
Three of Hearts
Ten of Diamonds
Ten of Diamonds
Four of Diamonds
Ace of Hearts
Queen of Spades
Two of Spades
Jack of Hearts
Six of Spades
Two of Spades
Seven of Clubs
Two of Spades
Eight of Spades
Nine of Clubs
Seven of Hearts
Four of Clubs
Seven of Spades
Nine of Spades
Queen of Spades
Five of Hearts

... sorting the cards ...

Four of Diamonds
Ten of Diamonds
Ten of Diamonds
Four of Clubs
Seven of Clubs
Nine of Clubs
Ace of Hearts
Three of Hearts
Five of Hearts
Seven of Hearts
Jack of Hearts
Two of Spades
Two of Spades
Two of Spades
Six of Spades
Seven of Spades
Eight of Spades
Nine of Spades
Queen of Spades
Queen of Spades