#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RANK 13
#define MAX_SUIT 4
enum hand
{
royal_flush = 1,
straight_flush,
four_of_a_kind,
fullhouse,
flush,
straight,
three_of_a_hand,
two_pairs,
pair,
high_card
};
const int card_nums = 5;
const char rank[MAX_RANK] = { 'a', '2', '3', '4', '5', '6', '7', '8', '9', 't', 'j', 'q', 'k' };
const char suit[MAX_SUIT] = { 'd', 'c', 'h', 's' };
int mycard[MAX_RANK + 1][MAX_SUIT] = { 0 };
void deal(void);
enum hand check(void);
void hand_print(enum hand);
void reset(void);
int main()
{
while (1)
{
deal();
hand_print(check());
reset();
}
return 0;
}
void deal(void)
{
int cnt = card_nums;
while (cnt)
{
char rr, ss;
int rr_i = 0, ss_i = 0;
printf("Enter a card: ");
while ((rr = getchar()) == '\n')
;
if (rr == '0')
{
exit(EXIT_SUCCESS);
}
while ((ss = getchar()) == '\n')
;
while (getchar() != '\n')
;
for (; rr_i < MAX_RANK && rank[rr_i] != rr; rr_i++)
;
for (; ss_i < MAX_SUIT && suit[ss_i] != ss; ss_i++)
;
if (rr_i == MAX_RANK || ss_i == MAX_SUIT)
{
printf("Bad card; ignored.\n");
continue;
}
if (mycard[rr_i][ss_i])
{
printf("Duplicate card; ignored.\n");
continue;
}
cnt--;
mycard[rr_i][ss_i] = 1;
if (rr_i == 0) mycard[MAX_RANK][ss_i] = 1;
}
}
enum hand check(void)
{
int rank_cnt[MAX_RANK + 1] = { 0 };
int suit_cnt[MAX_SUIT] = { 0 };
int max_rank_cnt = 0;
int max_suit_cnt = 0;
int pair_cnt = 0;
for (int i = 0; i < MAX_RANK; i++)
{
for (int j = 0; j < MAX_SUIT; j++)
{
if (mycard[i][j])
{
rank_cnt[i]++;
if (i == 0) rank_cnt[MAX_RANK]++;
max_rank_cnt = rank_cnt[i] > max_rank_cnt ? rank_cnt[i] : max_rank_cnt;
suit_cnt[j]++;
max_suit_cnt = suit_cnt[j] > max_suit_cnt ? suit_cnt[j] : max_suit_cnt;
}
}
}
for (int i = 0; i < MAX_RANK; i++)
{
if (rank_cnt[i] == 2)
{
pair_cnt++;
}
}
if (max_suit_cnt >= 5)
{
int suit_selected = 0;
for (int i = 0; i < MAX_SUIT; i++)
{
if (suit_cnt[i] >= 5)
{
suit_selected = i;
break;
}
}
for (int i = 0; i < MAX_RANK - 3; i++)
{
if (mycard[i][suit_selected] && mycard[i + 1][suit_selected] && mycard[i + 2][suit_selected]
&& mycard[i + 3][suit_selected] && mycard[i + 4][suit_selected])
{
if (i == MAX_RANK - 4) return royal_flush;
return straight_flush;
}
}
}
if (max_rank_cnt == 4) return four_of_a_kind;
if (max_rank_cnt == 3 && pair_cnt) return fullhouse;
if (max_suit_cnt >= 5) return flush;
for (int i = 0; i < MAX_RANK - 3; i++)
{
if (rank_cnt[i] && rank_cnt[i + 1] && rank_cnt[i + 2] && rank_cnt[i + 3] && rank_cnt[i + 4])
{
return straight;
}
}
if (max_rank_cnt == 3) return three_of_a_hand;
if (pair_cnt >= 2) return two_pairs;
if (pair_cnt == 1) return pair;
return high_card;
}
void hand_print(enum hand h)
{
char* hand[] =
{
"",
"Royal flush",
"Straight flush",
"Four of a kind",
"Fullhouse",
"Flush",
"Straight",
"Three of a hand",
"Two pairs",
"Pair",
"High card"
};
printf("%s\n\n",hand[h]);
}
void reset(void)
{
memset(mycard, 0, sizeof(mycard));
}