So far my best ideas have been as fallows
A) Represent a “card” in one structure and have a “deck” in another
a deck being an array of 52 cards and a card being 2 chars one for and rank one for suit.
B) The second seems like it might be easier to manage but less obvious in code. Creating an array of ints each with a different value ranging from 1-52. Then crating a conversion function that would translate the value to a card structure that would have a string for the suit and a string for the rank. The value of zero could indicate a card that has not been “dealt”.
Just trying to find a better way of doing this.
5
It depends on the cards (joker included or not), but I’m using situation B mostly. However I use the first two bits of the integer value to define the color and the rest to define the card value making them together the card. Then I can get the color or value from the card much quicker with bitwise (or mod, divide and multiplication) operations. We simply store two integer values into one integer. The card value we store starting from the third bit, so we can simply multiply that value by four or use a bitshift of 2. Then we add the card color (0, 1, 2 and 3) which is never more than 2 bits in the first 2 bits of the card.
Assuming that the second card is a two and the second color is clubs. So a 2 of clubs will be stored as (binary) 100 + 1 = 101 which is 5 in decimals. If we have card 5 we can use mod and divide because card / 4
will tell us the card value and card % 4
will tell us the card color.
4
So you either want to represent a card as an int
, with the need to convert to suit/rank whenever you need that, or you represent it as a
struct Card
{
char Suit;
char Rank;
};
with no need to convert to suit/rank whenever you need those values. Performance and memory resources won’t differ much between both approaches, I guess they are completely neglectable. So it all boils down to “which alternative is more readable” – and it seems very obvious to me that using a struct Card
to represent cards will be much more readable than using an int and doing any unnecessary encoding / decoding.
EDIT: the only reason I can think of why one should use the integer representation is when you need the cardnumber (1…52) mainly as an array index, and you expect the usage as a card with Suit and Rank as very seldom needed in your program.
1