Design a deck of cards


  • 0
    L

    Design a deck of 52 cards (hearts,diamonds,clubs and spades).
    Implement the following methods using that deck of cards
    a) Shuffle method that returns a shuffled deck.
    b) calculateHandValue method that returns the total value of the hand dealt to a person.
    *For simplification, consider the Ace card to have a value of 1 (always).
    King,Queen and Jack have a value of 10.


  • 0
    public class Deck
        {
            public const int NUM_CARDS = 52;
    
            public enum Suit
            {
                Diamonds,
                Hearts,
                Clubs,
                Spades
            }
    
            public enum Face
            {
                None,
                Jack,
                Queen,
                King,
                Ace
            }
    
    
            public class Card
            {
    
                public Suit Suit { get; set; }
                public Face Face { get; set; }
                public int Value { get; set; }
                
                public Card(Suit suit, Face face, int value)
                {
                    Suit = suit;
                    Face = face;
                    Value = value;
                }
            }
    
            public List<Card> Cards { get; }
    
            public Deck()
            {
    
                Cards = new List<Card>();
                
                for (int i = 0; i < 4; i++)
                {
                    // Ace
                    Cards.Add( new Card((Suit)i, Face.Ace, 1)); 
    
                    // 2 - 10
                    for (int j = 2; j < 11; j++)
                    {
                        Cards.Add(new Card((Suit)i, Face.None, j));
                    }
    
                    // Jack - King
                    for(int j = 1;j<4;j++)
                    {
                        Cards.Add(new Card((Suit)i, (Face)j, 10));
                    }
                }
    
            }
    
            public List<Card> Shuffle()
            {
                Random rand = new Random();
                for (int i = 0; i < NUM_CARDS; i++)
                {
                               
                    int randomInt = rand.Next(0, 51);
                    Card temp = Cards[i];
                    Cards[i] = Cards[randomInt];
                    Cards[randomInt] = temp;
                }
    
                return Cards;
            }
    
            public int CalculateHandValue(List<Card> hand)
            {
                int handValue = 0;
    
                foreach (Card card in hand)
                {
                    handValue += card.Value;
                }
    
                return handValue;
            }
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.