Write a program to simulate a deck of 52 playing cards. Represent your deck as a
ID: 3554674 • Letter: W
Question
Write a program to simulate a deck of 52 playing cards.
Represent your deck as a 2D Array where the value in
the cell is the position of the card in the deck.
Represent the names for the suits and faces as
an array of Strings.
Write an algorithm to shuffle the deck.
Display the deck. For Example:
1 Jack of Spades
2 Deuce of Diamonds
3 Three of Diamonds
4 King of Spades
5 Eight of Clubs
6 King of Diamonds
7 Six of Clubs
8 Six of Spades
9 Eight of Hearts
...
Deal 2, 3 or 4 hands of five cards from the shuffled deck.
Explanation / Answer
( Done EXACTLY following the mentioned Specifications )
Code :
#include<ctime>
#include<string>
#include<cstdlib>
#include<iostream>
using namespace std;
void shuffle(int[][2]);
int main()
{
int hands, num, type, deck[52][2], hand[4][2], removed[4][52]={0};
string suit[4]= {"hearts","diamonds","spades","clubs"};
string card[13]= {"Ace","Deuce","Three","Four","Five","Six",
"Seven","Eight","Nine","Ten","Jack","Queen","King"};
srand(time(NULL));
shuffle(deck);
cout<<"Deck-before shuffle : --------------------- ";
for(int i=0; i<52; i++)
cout<<card[deck[i][1]]<<" of "<<suit[deck[i][0]]<<endl;
cout<<endl;
shuffle(deck);
cout<<"Deck-after shuffle : -------------------- ";
for(int i=0; i<52; i++)
cout<<card[deck[i][1]]<<" of "<<suit[deck[i][0]]<<endl;
cout<<" Enter number of hands of 5 cards each to take : ";
cin>>hands;
cout<<endl;
for(int i=0; i<hands; i++)
{
cout<<" Hand "<<i+1<<" : ----------------"<<endl;
for(int j=0; j<5; j++)
{
num=rand()%13;
type=rand()%4;
if(!removed[type][num])
{
cout<<card[num]<<" of "<<suit[type]<<endl;
removed[type][num]=1;
}
else j--;
}
}
cout<<endl;
return 0;
}
void shuffle(int deck[][2])
{
int i,j,num,type;
bool cards[4][13];
for(i=0; i<4; i++)
for(j=0; j<13; j++)
cards[i][j]=false;
for(j=0; j<52; j++)
{
do
{
num=rand()%13;
type=rand()%4;
}while(cards[type][num]);
deck[j][0]=type;
deck[j][1]=num;
cards[type][num]=true;
}
return;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.