Answer to Question #180800 in C++ for simisola oluwaseyitan alabi

Question #180800

Utilize an array structure in conjunction to simulate our card deck. 

Use the following array structures to assist in representing a card: 

string face [13] = { "Ace ", "Deuce", "Three", "Four", "Five", "Six", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};

string suit[4] = {"Hearts", "Diamonds", "Clubs", "Spade"};


Write a program that utilizes random number generation, just as you have in the past, to

generate a random face and random suit. This, of course, will be a “card”.

Use a loop to generate and print five cards.

Example Output:

Card 1: Five of Spades

Card 2: Queen of Hearts

Card 3: Seven of Spades

Card 4: Two of Clubs

Card 5: Ace of Diamonds


1
Expert's answer
2021-04-13T06:30:26-0400
#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<random>
#include<algorithm>

struct Card{
    enum Suit {Spades,Hearts,Clubs,Diamonds };
    enum Face {Ace,Deuce,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Jack,Queen,King};
    static const unsigned longestFace = 5;
    Suit suit;
    Face face;
 };

std::string as_string(Card::Suit suit){
    static const char* suit_str[] = {"Spades","Hearts","Clubs","Diamonds"};
    return suit_str[suit];
}

std::string as_string(Card::Face face){
    static const char* face_str[]={"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven","Eight", "Nine", "Ten", "Jack", "Queen", "King"
    };

    return face_str[face];
}

std::ostream& operator<<(std::ostream& os, Card c){
    os << std::right << std::setw(Card::longestFace);
    os << as_string(c.face) << " of " << as_string(c.suit) ;

    return os;
}

template <typename iter_type>
void printCards(iter_type beg, iter_type end){
    while (beg != end)
        std::cout << *beg++ << '\n';
}

int main(){
    std::vector<Card> cards;
    for ( unsigned s=0; s<4; ++s)
        for (unsigned f = 0; f < 13; ++f)
            cards.push_back({ Card::Suit(s), Card::Face(f) });

    std::mt19937 rng((std::random_device())());

    for (unsigned runs = 0; runs < 5; ++runs)
    {
        std::shuffle(cards.begin(), cards.end(), rng);
        printCards(cards.begin(), cards.begin() + 5);
        std::cout << '\n';
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS