Please post the solution and output. Please save the program with the name \'car
ID: 3858428 • Letter: P
Question
Please post the solution and output. Please save the program with the name 'cards.c'.
a) Write a structure (struct card) that will represent a card in a standard deck of playing cards. You will need to represent both the suit (clubs, diamonds, hearts or spades) as well as rank (K, Q, J, 10, 9, 8, 7, 6, 5, 4, 3, 2, A) of each card. Note that a deck of playing cards can be represented as an array declared as
struct card deck[52];
b) Write a function that will perform a perfect shuffle on a deck of cards represented using data structures from part a. In a perfect shuffle, the deck is broken exactly in half and rearranged so that the first card is followed by the 27th card, followed by the second card, followed by the 28th card, and so on.
c) Write a program that tests how many perfect shuffles are necessary to return the deck to its original configuration.
Explanation / Answer
#include <stdio.h>
#define UNUSED(x) (void)(x)
enum card_suit { HEARTS, DIAMONDS, SPADES, CLUBS };
struct card
{
enum card_suit suit;
int value;
};
const char *suit_name(const struct card *card)
{
switch (card->suit)
{
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case SPADES: return "Spades";
case CLUBS: return "Clubs";
default: return "INVALID"; /* or Joker? but this requires 54 cards */
}
}
void print_card(const struct card *card)
{
static const char *values[13] =
{
"Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack",
"Queen", "King", "Ace"
};
printf("%s of %s ", values[card->value - 2], suit_name(card));
}
void init_cards(struct card cards[52])
{
int i;
for (i = 0; i < 13; ++i)
{
cards[i].suit = HEARTS;
cards[i].value = i + 2;
cards[i + 13].suit = DIAMONDS;
cards[i + 13].value = i + 2;
cards[i + 26].suit = SPADES;
cards[i + 26].value = i + 2;
cards[i + 39].suit = CLUBS;
cards[i + 39].value = i + 2;
}
}
int main(int argc, const char *argv[])
{
int i;
struct card cards[52];
init_cards(cards);
for (i = 0; i < 52; ++i)
print_card(cards + i);
UNUSED(argc);
UNUSED(argv);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.