Originally Posted by
Bubba
I'm a bit late to this thread but you don't have to use a structure and could just use the raw numbers. Suits are composed of a set number of cards so you could translate the number into whatever output you want.
Figuring out how to shuffle the deck by passing through the deck exactly one time and yet ensuring every card is shuffled is a very good exercise. In fact I've used it as an interview question b/c it allows me to see someone work through a problem step by step which is invaluable when it comes to analyzing how different people approach problems.
I'd be interested to see your first attempt at your own shuffle algorithm here in this thread. This will definitely get you thinking and I'm curious as to what you will come up with.
Here is my take at the shuffle algorithm:
Code:
#ifndef CARD_H_
#define CARD_H_
struct Deck_Card
{
int val;
int suit;
};
class Card
{
private:
Deck_Card Deck[52];
public:
Card();
~Card();
void Card_Shuffle(int nn = 52);
void Show();
};
#endif
Code:
#include <iostream>
#include "card.h"
#include <cstdlib>
#include <ctime>
using namespace std;
Card:: Card()
{
int i;
int j;
// Generating the ordered set/ordered Deck of Card
// i to generate number from 1-13
// j to generate the suites;
for ( i = 0; i < 13; i++ )
{
for(j = 0; j < 4; j++)
{
if ( (4*i+j) > 52) break;
Deck[4*i+j].val = i+1;
Deck[4*i+j].suit = j;
}
}
}
Card::~Card()
{}
void Card::Card_Shuffle(int nn)
{
// nn is the number of times to switch position of 2 random cards. Default nn=52
srand(time(NULL));
Deck_Card temp;
// n and m are the position of 2 cards in a deck.
int n,m;
int i;
for (i = 0 ; i < nn ; i++)
{
// generating two random position
n = rand() % 52;
m = rand() % 52;
// n and m must have different values
while ( n == m)
{
n = rand() % 52;
m = rand() % 52;
}
// switch the position
temp = Deck[n];
Deck[n] = Deck [m];
Deck[m] = temp;
}
}
void Card::Show()
{
string suit[4] = {"Hearts","Diamonds","Club", "Spades"};
for (int i = 0; i < 52; i++)
cout << Deck[i].val << " of "<<suit[ Deck[i].suit] << endl;
}
Code:
#include <iostream>
#include "card.h"
int main()
{
Card deck1;
deck1.Show();
deck1.Card_Shuffle();
std:: cout << " Shuffled Deck: " << std::endl;
deck1.Show();
return 0;
}
Here is my take on this one. This was a good exercise. I don't quite understand what you meant by "passing through the deck exactly one time." What I did was just generate the random positions of two cards in the deck and switch them. The shuffle is quite good after just iterate that for 52 times. I think a better way would be generating a set random unique number from 0 to 51. The uniqueness property makes it harder because I don't think C would check for that. I'll try that method later.
I guess i could use enqueue and dequeue to take the 2 set of 5 cards out. And, if I want to reshuffle the rest of the cards, then I could've use dynamic array for "Deck".