How to implement a dealer class without storing a deck of cards?

前端 未结 8 1274
长发绾君心
长发绾君心 2021-02-09 19:07
  • Question

    Even only 52 cards, the permutationIndex where I describe in Explanations section, would be a huge number; it is

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-09 19:32

    I really don't get your question, but I interpret it like this: you want to calculate the permutationIndex of a sequence of 52 cards. A given permutation index maps one-to-one to a sequence of cards. Since there are 52! possible arrangements of 52 cards, you'll need at least 226 bits, or 29 bytes. So, your permutationIndex will already be very big!

    Since your permutation index is already 29 bytes long, some extra bytes won't make much of a difference and make the solution a lot easier.


    For example, you could map each letter of the Latin alphabet to a card. Given that we have 26 lower case letters, 26 upper case letters, we have lo and behold 52 letters available to represent the 52 cards.

      abcdefghijklm      nopqrstuvwxyz
    ♥ A234567890JQK    ♦ A234567890JQK
    
      ABCDEFGHIJKLM      NOPQRSTUVWXYZ
    ♣ A234567890JQK    ♠ A234567890JQK
    

    Now you can make a string of 52 letters. Each unique letter string represents a unique permutation of 52 cards. With this you can:

    • Generate a random string of letters to get a random permutation.
    • Immediately find out what card is where just by looking at the letter at a given position.
    • Shuffle, reorder, insert and remove cards easily.

    Each character in a string is represented (in C#) as a 16-bit Unicode value, but for 52 cards you would only need 6 bits. So you have some more options to choose a representation:

    1. 832 bits, or 104 bytes: string of 52 Unicode characters
    2. 416 bits, or 52 bytes: array of 52 bytes
    3. 320 bits, or 40 bytes: array of 10 32-bit integers to hold 52 * 6 bits
    4. 312 bits, or 39 bytes: array of 39 bytes to hold 52 * 6 bits
    5. 226 bits, or 29 bytes: absolute lower bound

    Representations 3 and 4 require quite some clever bit fiddling to get the 6 bits for a specific card out of the sequence. I would recommend representation 2, which preserves most of the advantages mentioned above.


    When you are using a binary representation instead of a character string representation, then you can create an enum with a unique value for each card, and use that:

    public enum Cards : byte
    {
        HeartsAce
        HeartsTwo
        // ...
        HeartsTen
        HeartsJack
        HeartsQueen
        HeartsKing
        DiamondsAce
        DiamondsTwo
        // ...
        SpadesTen
        SpadesJack
        SpadesQueen
        SpadesKing
    }
    

提交回复
热议问题