473,657 Members | 2,634 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner Question--rand( )

I've just begun learning C++ and I'm trying to write a program to shuffle a
deck of cards. I've succeeded....fo r 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[i] = rand();
shuffledDeck[ randomNumber[i] ] = cardDeck[i];
}

for (map<int,string >::iterator p = shuffledDeck.be gin(); p !=
shuffledDeck.en d(); ++p)
{
cout << p->first
<< "\t"
<< p->second
<< endl;
}

if (shuffledDeck.s ize () != 52) //indicates duplicate random numbers
{
sort(randomNumb er, randomNumber+52 ); //easy viewing
cout << endl
<< "DUPLICATE RANDOM NUMBERS!\n\n";
for (int i=0; i<52; ++i)
cout << randomNumber [i]
<< "\t";

cout << "\n";
}

cout << endl;
system("PAUSE") ;
return 0;
}
Jul 19 '05 #1
23 6013
hedylogus wrote:

every now and
then rand() produces duplicate random numbers
Of course it does. If it didn't, the numbers wouldn't be random.
How do I avoid this???


std::random_shu ffle.

--

"To delight in war is a merit in the soldier,
a dangerous quality in the captain, and a
positive crime in the statesman."
George Santayana

"Bring them on."
George W. Bush
Jul 19 '05 #2
"Pete Becker" <pe********@acm .org> wrote in message
news:3F******** *******@acm.org ...
hedylogus wrote:

every now and
then rand() produces duplicate random numbers
Of course it does. If it didn't, the numbers wouldn't be random.


Repeat values are a consequence of finite numbers of bits computed by the
algorithm, not randomness itself. Of course with certain lousy
implementations of rand() only a miserly 15 bits (the absolute minimum
allowed by the standard) are provided, resulting in repetition in very short
run lengths.
How do I avoid this???


std::random_shu ffle.


Or get a decent random number generator (31 bits or more). They are readily
available. You will still get repeats if you let your program run for the
rest of your life.

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 19 '05 #3
Cy Edmunds wrote:
"Pete Becker" <pe********@acm .org> wrote in message
news:3F******** *******@acm.org ...
hedylogus wrote:
every now and
then rand() produces duplicate random numbers


Of course it does. If it didn't, the numbers wouldn't be random.

Repeat values are a consequence of finite numbers of bits computed by the
algorithm, not randomness itself. Of course with certain lousy
implementations of rand() only a miserly 15 bits (the absolute minimum
allowed by the standard) are provided, resulting in repetition in very short
run lengths.


That's silly. If the numbers were truly random, the expected number of
draws before a duplicate would be much less than the number of possible
results.
How do I avoid this???


std::random_s huffle.

Or get a decent random number generator (31 bits or more). They are readily
available. You will still get repeats if you let your program run for the
rest of your life.


If only 52 draws are made, what difference does drawing from 2^32 values
rather than 2&16 make? The chance of some number occurring twice in
those 52 draws would presumably still be significantly greater than
zero in the latter case.

(To the OP:)
Search for Fisher-Yates shuffle for the usual (optimal) implementation
of random_shuffle.

Regards,
Buster

Jul 19 '05 #4
Buster Copley wrote:
If only 52 draws are made, what difference does drawing from 2^32 values
rather than 2&16 make? The chance of some number occurring twice in
those 52 draws would presumably still be significantly greater than
zero in the latter case.
That is, 2^16, and I hope you can guess which case I meant.
Regards,
Buster


Jul 19 '05 #5
Cy Edmunds wrote:

"Pete Becker" <pe********@acm .org> wrote in message
news:3F******** *******@acm.org ...
hedylogus wrote:

every now and
then rand() produces duplicate random numbers
Of course it does. If it didn't, the numbers wouldn't be random.


Repeat values are a consequence of finite numbers of bits computed by the
algorithm, not randomness itself.


No. Suppose you roll a six-sided die five times and you get 5, 2, 3, 6,
and 1. Do you expect 4 to come up next?

Of course with certain lousy implementations of rand() only a miserly 15 bits (the absolute minimum
allowed by the standard) are provided, resulting in repetition in very short
run lengths.
How do I avoid this???


std::random_shu ffle.


Or get a decent random number generator (31 bits or more).


Won't help, if your technique is wrong. That's why random_shuffle isn't
called rand. They do different things.

--

"To delight in war is a merit in the soldier,
a dangerous quality in the captain, and a
positive crime in the statesman."
George Santayana

"Bring them on."
George W. Bush
Jul 19 '05 #6


"hedylogus" <xx**********@y ahoo.xxx> wrote in message
news:<%JhUa.147 299$H17.51207@s ccrnsc02>
....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.


Despite quite a few answers already, I will take a stab at this in a
'newbie' context, since I am barely, if at all, past that stage myself.
rand() produces a stream of psuedo-random numbers based on a seed, the
computer clock in your case.
rand() cannot ensure that there are no duplicates in that stream. I can
think of three options for you in this case:

1) Find a more sophisticated random number generator. This is reasonable,
but IMHO, you would be better off with #2 or #3

2) Develop a test condition so you can "draw again" if the random number
tries to draw more than once from the same spot in CardDeck[]. This is a
reasonable solution, except for the fact that your code show s that you
have at least a passing familiarity with STL.

3) Go for the double bonus: go for random_shuffle like Rolf suggested. Not
only will you solve your duplication problem, your code will be much smaller
and cleaner. The bonus-bonus is that your code will be very readable, a
definite plus as far as grading goes.


Jul 19 '05 #7
Danny Anderson wrote:

1) Find a more sophisticated random number generator. This is reasonable,
but IMHO, you would be better off with #2 or #3
This is not the problem.

2) Develop a test condition so you can "draw again" if the random number
tries to draw more than once from the same spot in CardDeck[]. This is a
reasonable solution, except for the fact that your code show s that you
have at least a passing familiarity with STL.
This becomes slower as you use up numbers. Bad approach.

3) Go for the double bonus: go for random_shuffle like Rolf suggested. Not
only will you solve your duplication problem, your code will be much smaller
and cleaner. The bonus-bonus is that your code will be very readable, a
definite plus as far as grading goes.


Or learn how to do it yourself. It's not that hard, and provides some
useful insights.

--

"To delight in war is a merit in the soldier,
a dangerous quality in the captain, and a
positive crime in the statesman."
George Santayana

"Bring them on."
George W. Bush
Jul 19 '05 #8
> > 3) Go for the double bonus: go for random_shuffle like Rolf suggested.
Not
only will you solve your duplication problem, your code will be much smaller and cleaner. The bonus-bonus is that your code will be very readable, a
definite plus as far as grading goes.


Or learn how to do it yourself. It's not that hard, and provides some
useful insights.


Maybe so- my take was that the guy was using STL structures and some general
algorithms like sort(), but didn't seem to know about random_shuffle. In
that case, I think random_shuffle is a really good choice. I understand the
DIY rationalization , but it seems to me a lot of stuff works in the opposite
order: learn to use the tools available first, the improve and fabricate new
better tools when the need arises.

Just an opinion, don't flog me for it too much. :)

Danny
Jul 19 '05 #9
"Pete Becker" <pe********@acm .org> wrote in message
news:3F******** *******@acm.org ...
Cy Edmunds wrote:

"Pete Becker" <pe********@acm .org> wrote in message
news:3F******** *******@acm.org ...
hedylogus wrote:
>
> every now and
> then rand() produces duplicate random numbers

Of course it does. If it didn't, the numbers wouldn't be random.


Repeat values are a consequence of finite numbers of bits computed by the algorithm, not randomness itself.


No. Suppose you roll a six-sided die five times and you get 5, 2, 3, 6,
and 1. Do you expect 4 to come up next?


No, I don't. But if I did get a 4, on the seventh roll I would certainly get
a duplicate. This has nothing to do with randomness. It only has to do with
the fact that a die only has six sides. Hence:

"Repeat values are a consequence of finite numbers of bits computed by the
algorithm, not randomness itself."

<snip>

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3073
by: Richard B. Kreckel | last post by:
Hi! I was recently asked what book to recommend for a beginner in C++. I am convinced that you needn't study C in depth before learning C++ (though it helps), but cannot find any beginner's book which isn't aimed at people coming from C/Pascal/Java/Delpi/whatever... However, there seem to be plenty such books for all those other languages. Is there really no literature for people trying to learn programming by starting with C++? ...
8
2371
by: Grrrbau | last post by:
I'm a beginner. I'm looking for a good C++ book. Someone told me about Lafore's "Object-Oriented Programming in C++". What do you think? Grrrbau
7
2926
by: Rensjuh | last post by:
Hello, does someone have / know a good C++ tutorial for beginnners? I would prefer Dutch, but English is also fine. Hoi, heeft / kent iemand nog een goede C++ tutorial voor beginners? Het liefste in Nederlands, maar Engels is ook goed. Thnx, Rensjuh
27
4359
by: MHoffman | last post by:
I am just learning to program, and hoping someone can help me with the following: for a simple calculator, a string is entered into a text box ... how do I prevent the user from entering a text instead of a number, or give an error message? Also, how can I make the program verify there are two valid entries in txtBox1 and txtBox2 to then ENABLE the button operators (ie +, -, /, *).
18
2914
by: mitchellpal | last post by:
Hi guys, am learning c as a beginner language and am finding it rough especially with pointers and data files. What do you think, am i being too pessimistic or thats how it happens for a beginner? Are there better languages than c for a beginner? For instance visual basic or i should just keep the confidence of improving?
20
2279
by: weight gain 2000 | last post by:
Hello all! I'm looking for a very good book for an absolute beginner on VB.net or VB 2005 with emphasis on databases. What would you reccommend? Thanks!
5
2735
by: macca | last post by:
Hi, I'm looking for a good book on PHP design patterns for a OOP beginner - Reccommendations please? Thanks Paul
10
4443
by: Roman Zeilinger | last post by:
Hi I have a beginner question concerning fscanf. First I had a text file which just contained some hex numbers: 0C100012 0C100012 ....
10
2146
by: hamza612 | last post by:
I want to start learning how to program. But I dont know where to start. From what I've heard so far c++ is not a good lang. to learn as a beginner because its very complicated compared to others like python, ruby etc. I would like to know if there is a prerequisite to learning any computer language, is there something I have to learn before learning any computer language, like a basic or core?
22
18133
by: ddg_linux | last post by:
I have been reading about and doing a lot of php code examples from books but now I find myself wanting to do something practical with some of the skills that I have learned. I am a beginner php programmer and looking for a starting point in regards to practical projects to work on. What are some projects that beginner programmers usually start with? Please list a few that would be good for a beginner PHP programmer to
0
8407
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8319
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8837
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8739
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6175
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5638
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4329
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2739
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1732
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.