H
hedylogus
I've just begun learning C++ and I'm trying to write a program to shuffle a
deck of cards. I've succeeded....for the most part....but every now and
then rand() produces duplicate random numbers causing me to "lose" a card.
How do I avoid this??? I've attached my code below for reference. Thanks
in advance.
------------------------
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
string cardDeck[] = {"As", "Ah", "Ad", "Ac",
"2s", "2h", "2d", "2c",
"3s", "3h", "3d", "3c",
"4s", "4h", "4d", "4c",
"5s", "5h", "5d", "5c",
"6s", "6h", "6d", "6c",
"7s", "7h", "7d", "7c",
"8s", "8h", "8d", "8c",
"9s", "9h", "9d", "9c",
"Ts", "Th", "Td", "Tc",
"Js", "Jh", "Jd", "Jc",
"Qs", "Qh", "Qd", "Qc",
"Ks", "Kh", "Kd", "Kc"};
map<int,string> shuffledDeck;
int randomNumber[52]; //used for debug purposes
int main()
{
srand( time(NULL) );
cout << "Current seed value: "
<< time(NULL)
<< "\n\n";
for (int i=0; i<52; ++i)
{
randomNumber = rand();
shuffledDeck[ randomNumber ] = cardDeck;
}
for (map<int,string>::iterator p = shuffledDeck.begin(); p !=
shuffledDeck.end(); ++p)
{
cout << p->first
<< "\t"
<< p->second
<< endl;
}
if (shuffledDeck.size () != 52) //indicates duplicate random numbers
{
sort(randomNumber, randomNumber+52); //easy viewing
cout << endl
<< "DUPLICATE RANDOM NUMBERS!\n\n";
for (int i=0; i<52; ++i)
cout << randomNumber
<< "\t";
cout << "\n";
}
cout << endl;
system("PAUSE");
return 0;
}
deck of cards. I've succeeded....for the most part....but every now and
then rand() produces duplicate random numbers causing me to "lose" a card.
How do I avoid this??? I've attached my code below for reference. Thanks
in advance.
------------------------
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
string cardDeck[] = {"As", "Ah", "Ad", "Ac",
"2s", "2h", "2d", "2c",
"3s", "3h", "3d", "3c",
"4s", "4h", "4d", "4c",
"5s", "5h", "5d", "5c",
"6s", "6h", "6d", "6c",
"7s", "7h", "7d", "7c",
"8s", "8h", "8d", "8c",
"9s", "9h", "9d", "9c",
"Ts", "Th", "Td", "Tc",
"Js", "Jh", "Jd", "Jc",
"Qs", "Qh", "Qd", "Qc",
"Ks", "Kh", "Kd", "Kc"};
map<int,string> shuffledDeck;
int randomNumber[52]; //used for debug purposes
int main()
{
srand( time(NULL) );
cout << "Current seed value: "
<< time(NULL)
<< "\n\n";
for (int i=0; i<52; ++i)
{
randomNumber = rand();
shuffledDeck[ randomNumber ] = cardDeck;
}
for (map<int,string>::iterator p = shuffledDeck.begin(); p !=
shuffledDeck.end(); ++p)
{
cout << p->first
<< "\t"
<< p->second
<< endl;
}
if (shuffledDeck.size () != 52) //indicates duplicate random numbers
{
sort(randomNumber, randomNumber+52); //easy viewing
cout << endl
<< "DUPLICATE RANDOM NUMBERS!\n\n";
for (int i=0; i<52; ++i)
cout << randomNumber
<< "\t";
cout << "\n";
}
cout << endl;
system("PAUSE");
return 0;
}