data representation of cards

Post: #1
I am working on a poker game. Current, I represent a players 5 card hand as an array 5 shorts long. Each short contains a number in the range 0 to 51 representing one of the 52 cards. To find the suite of a card I divide an element by 13 (0= diamonds, 1 = clubs, ...). To find the value of a card I mod an element by 13 (A=0,2=1,.. ,10=9,J=10,Q=1,K=12). This works fine until it comes to determining the value of a hand (fullhouse, straight, flush, etc.) The function that I have written that does this is full of /'s and %'s and is heavily looped. That is to say I think it is pretty inefficient.

I am considering changing my representation over to a bitwise representation that would allow me to use bitwise operators to find the value of a hand more quickly. However, I don't have a lot of experience with bitwise operation so I would like to run my new representation past the sages at idevgames (aka you, the reader) first.

The data would look be held in 4 shorts

unsigned short hand[4];

I understand a short is 16 bits long, so 4 shorts would be 64 bits long. That 52 bits to represent the possible cards and 12 bits of junk. Rather than having all the junk be at the end of the chunk of memory, I think it is best that each individual short represent all 13 cards of a particular suit with its last 3 bits being junk (0's actually). This will make it easier to determine the value of hand.

I know how to check for straights and flushes and therefore straightflushes.
Also checking for four of a kind is easy.

if( (((hand[0]&hand[1])&hand[2]&hand[3]) !=0 )
return four_of_a_kind;

But I am not sure how to efficiently check for and differentiate between full houses (ie AAA99) and two pair (AA99J) and three of a kind or a pair. Any one have any ideas?

Quote this message in a reply
Posts: 5,143
Joined: 2002.04
Post: #2
First, why are you concerned about efficiency here? Has performance proven to be a problem?

Second, whatever your representation, write yourself some readable accessors! For example, to take your current representation:

typedef unsigned short Card;
typedef unsigned short Suit;
typedef unsigned short Rank;

inline Suit getSuit(Card card) { return card / 13 }
inline Rank getRank(Card card) { return card % 13 }

Bingo -- instantly more readable.
Quote this message in a reply
Posts: 370
Joined: 2002.04
Post: #3
Even more readable would be using bitpacked structs, with just enough space to store everything...

Did you ever wonder why we had to run for shelter when the promise of a brave new world unfurled beneath the clear blue sky?
Quote this message in a reply
Post Reply