In: Computer Science
(In C++) Write a class 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 the rank (A, K, Q,
J, 10, 9, 8, 7, 6, 5, 4, 3, 2) of each card.
Write methods to
• Initialize the deck of cards
• Perform a perfect shuffle
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.
• Print the deck of cards
• Compare two decks of cards
Print out the initial, the deck after the first perfect shuffle,
and the final deck.
Print out how many perfect shuffles are necessary to return the
deck to its original configuration.
#include <iostream> #include <iomanip> #include <vector> using namespace std; class Card { string suit, rank; public: Card(string s, string r) { suit = s; rank = r; } string toString() { return rank + suit; } }; class Deck { vector<Card> cards; public: Deck() { string suits[] = {"C", "D", "H", "S"}; string ranks[] = {"A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"}; for(string s: suits) { for(string r: ranks) { cards.push_back(Card(s, r)); } } } void print() { int i = 0; for(Card c: cards) { cout << setw(4) << c.toString(); if(++i % 13 == 0) { cout << endl; } } cout << endl; } void perfectShuffle() { for(int i=0; i<26; i++) { Card c = cards[26+i]; cards.erase(cards.begin() + 26 + i); cards.insert(cards.begin() + 2*i + 1, c); } } bool isIdenticalToOriginalDeck() { string suits[] = {"C", "D", "H", "S"}; string ranks[] = {"A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2"}; int i = 0; for(string s: suits) { for(string r: ranks) { if(r+s != cards[i++].toString()) { return false; } } } return true; } }; int main() { Deck d; d.print(); cout << "After perfect shuffle: " << endl; d.perfectShuffle(); d.print(); int shuffleCount = 1; while(!d.isIdenticalToOriginalDeck()) { d.perfectShuffle(); shuffleCount++; } cout << "After " << shuffleCount << " perfect shuffles, The deck is identical" << endl; d.print(); }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.