so I have a linked list that's meant to represent a hand of five playing cards. I'm trying to write a function to check if the cards are a royal flush. The first thing I do is check if the suit of the all the cards is the same. The next bit is where I'm having trouble. My idea is that I'd check if any of the cards are a king (13). If there is one, then it would go through the list again checking for a queen, jack, ace, and 10, and if at any point a card isn't found, it returns 0. If all the cards are there and they have the same suit, the function returns 1. This is what I've got so far:
int royalFlush(card* pHand) {
card* temp = pHand;
if (!suitCheck(temp)) {
return 0;
}
else {
while (temp != NULL) {
//check if the card has the right face here
temp = temp->next;
}
}
}
int suitCheck(card* pHand) {
card* tmp;
tmp = pHand;
while (tmp != NULL) {
if (tmp->suit != tmp->next->suit) {
return(0);
}
tmp = tmp->next;
}
return(1);
}
I'm having trouble figuring out how to move from one card to the next and check if the face of each card has the correct value. I'm also unsure if this: tmp->next->suit is something that the compiler can read properly.
CodePudding user response:
Assuming the cards are sorted by suit and by descending value,
- If the hand is empty,
- Return false.
- Get the suit of the first card.
- Create array [ Ace, King, Queen, Jack, Ten ].
- Set
i
to the index of the first element of the array. - Set the current card to the first card.
- While the current card isn't empty and
i
is within the bounds of the array,- If the suit of the current card doesn't match the suit of the first card,
- Return false.
- If the rank of the current card doesn't match the rank corresponding to index
i
,- Return false.
- Increment
i
. - Make the current card the following card.
- If the suit of the current card doesn't match the suit of the first card,
- Return True.
Note that a linked list if a very weird structure to be using for a card game hand.
CodePudding user response:
Welcome to SO! Hope you enjoy your time here.
If you're able to modify the function signature a bit, you could do something like this:
int suitCheck(card *pHand, suit expected_suite)
{
if(pHand == NULL) {
return 0; /* You can remove this if you're absolutely sure the initial next of the original pHand is not NULL */
}
while(pHand) {
if(pHand->suite != expected_suite) {
return 0;
}
}
return 1;
}
Then you'd call it from the main code like so:
if(suitCheck(temp->next, temp->suite)) {
I'll leave it to you to imagine how to accomplish the same feat without modifying the function signature.