473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

unique numbers using srand( ) and rand( ) functions in C++

A handful of articles have been posted requesting information on how
to use these functions in addition to the time() function as the seed
to generate unique groups (sets) of numbers - each group consisting of
6 numbers - with a total of 50 groups of numbers.

A well-known girl that some publishing companies use to provide
introductory level textbooks to various Junior Colleges in the U.S.,
not surprisngly, asks for this same exact information in one of the
exercises that she presents in various editions of her Introductory
Courses for C++.

Unfortunately, the little girl forgets to tell you that these
functions cannot promise or guarantee such unique numbers to be
presented to you, now or ever!

Therefore, you as the programmer, must manipulate the output to
provide what you want. (It's nice to know that your instructors also
have the textbook with all of the answers readily available to them.
But if you wish to think they are that enlightened, go ahead.)

Below is one way, among many, to approach this exercise presented by
her highness in all of her glorious Zuk.

Just copy it and paste it and you'll get one way for executing this
exercise.


#include <iostream>
#include <fstream>//for declaring objects of the ofstream and ifstream
classes for a data file
#include <time.h>//for use of time() & symbolic constant NULL (also
defined in stdlib.h file)
#include <stdlib.h>//for use of rand() & srand() functions and
constants RAND_MAX & NULL
using namespace std;//precludes need of .h extension when importing
most header files

void main()
{
//declare and initialize variables
short count = 0;//used for counter to generate 50 groups of lottery
numbers
short lowNum = 1;//used for lowerbound number of rand() function
short highNum = 9;//used for upperbound number of rand() function
short numero = 1;//counter used for formatting output of lottery
numbers to the screen
short b = 0;//used for counter in while() loop that reads records
from data file

short siArray[6] = {0};/*declare and initialize short integer type
array containing 6
elements with 0 values for each element*/
srand(time(NULL));//initialize random number generator
ofstream send2file;//declare object of ofstream class for use with
data file
ifstream readfile;//declare object of ifstream class for use with
data file
send2file.open("T8Be08.dat", ios::out);/*use open function associated
with both ifstream and ofstream
classes to open data file*/

//heading and information
cout << "\t\t\tLottery Numbers" << endl << endl
<< "This program opens the data file \"T8Be08.dat\" and then stores
groups of" << endl
<< "lotto numbers that have 6 unique numbers to a group in the data
file." << endl
<< "There are 50 groups of numbers. The groups of numbers are
displayed to the" << endl
<< "screen - 3 groups per line." << endl << endl;
if(!send2file.fail())//if opening data file was successful
{
while(count != 50)
{

for(short x = 0; x <= 5; x++)
{
//generate numbers
siArray[x] = lowNum + rand() % (highNum - lowNum + 1);
//adjust numeric range from 1 - 54, i.e., 1 - 9, 10 - 18, 19 - 27,
etc.
lowNum = highNum + 1;
highNum = highNum + 9;

if(x == 5)
{
for(short y = 0; y <= 5; y++)
{

if(y == 5)
{
send2file << siArray[y] << endl;//keep each range of lotto
numbers on 1 line in data file
}
else
{
send2file << siArray[y] << '#';
}//end nested if-else

}//end nested for() loop
}//end nested if
}//end nested for() loop

//reintialize lowNum and highNum for range so that range does not
exceed 54
lowNum = 1;
highNum = 9;

/*increment counter so that group of 6 numbers are generated and
sent to data file
50 times*/
count++;
}//end while() loop

send2file.close();//use close() function associated with both
ifstream and ofstream classes to close file
}
else
{
cout << "Error opening data file." << endl;
}//end if-else

readfile.open("T8Be08.dat", ios::in);//open data file for input
if(readfile.fail())
{
cout << "Error opening data file." << endl;
}
else
{
for(short z = 0; z <= 5; z++)//read 1st record from the data file
{
readfile >> siArray[z];
readfile.ignore(1);/*consume # character betwwen numbers of each
record in data file
or the invisible newline ('\n') character at the end of
each record
int the file*/
cout << siArray[z] << " ";//display each number in a group (6 per
group) to the screen

}//end nested for() loop that reads 1st group of numbers from data
file

cout << " ";//put spacing between each group of numbers displayed
to the screen

while(b != 49)//read remaining records from the data file (50 in
all)
{

for(short z = 0; z <= 5; z++)
{
readfile >> siArray[z];
readfile.ignore(1);
cout << siArray[z] << " ";

if(z == 5)
{
cout << " ";
}//end nested if
}//end nested for() loop

numero++;//increment counter for screen formatting
//if 3 groups of lotto numbers are on the output screen, go to next
line
if(numero == 3)
{
cout << endl;
numero = 0;//reset counter that allows 3 groups of numbers to
appear per line
}

b++;/*increment counter up to 50 for the 50 groups of lotto numbers
to be read from the data file*/
}//end nested while() loop
}//end if-else

cout << endl;//spacing

}//end main function
Jul 22 '05 #1
4 10698

"August1" <an*********@hotmail.com> wrote in message
news:fc**************************@posting.google.c om...
[SNIP]

Unfortunately, the little girl forgets to tell you that these
functions cannot promise or guarantee such unique numbers to be
presented to you, now or ever!
Nobody ever claimed rand() provides unique numbers. It is a random number
generator and the only thing it should provide is pseudo-random numbers (of
whatever quality).

Therefore, you as the programmer, must manipulate the output to
provide what you want.
Isn't this always the case? IMHO there is no such thing as a free meal.

[SNIP]
Below is one way, among many, to approach this exercise presented by
her highness in all of her glorious Zuk.

Just copy it and paste it and you'll get one way for executing this
exercise.
What exactly is the benefit or spreading a "solution" to people who should
learn something while tackling a problem? If this is the way it should work
then you'd end up with loads of people claiming they can develop software
even though they are not capable of solving the simplest of problems.


#include <iostream>
#include <fstream>//for declaring objects of the ofstream and ifstream
classes for a data file
#include <time.h>//for use of time() & symbolic constant NULL (also
defined in stdlib.h file)
#include <stdlib.h>//for use of rand() & srand() functions and
constants RAND_MAX & NULL
using namespace std;//precludes need of .h extension when importing
most header files
I'd suggest that you acquaint yourself with current standard headers
(cstdlib, ctime)

void main()
I guess this topic has already been beaten to death - main does not return
void but int!
{
//declare and initialize variables
short count = 0;//used for counter to generate 50 groups of lottery
numbers
short lowNum = 1;//used for lowerbound number of rand() function
short highNum = 9;//used for upperbound number of rand() function
short numero = 1;//counter used for formatting output of lottery
numbers to the screen
short b = 0;//used for counter in while() loop that reads records
from data file

short siArray[6] = {0};/*declare and initialize short integer type
array containing 6
elements with 0 values for each element*/
srand(time(NULL));//initialize random number generator
ofstream send2file;//declare object of ofstream class for use with
data file
ifstream readfile;//declare object of ifstream class for use with
data file
send2file.open("T8Be08.dat", ios::out);/*use open function associated
with both ifstream and ofstream
classes to open data file*/
Why don't you pass the filename to the ctor?
//heading and information
cout << "\t\t\tLottery Numbers" << endl << endl
<< "This program opens the data file \"T8Be08.dat\" and then stores
groups of" << endl
<< "lotto numbers that have 6 unique numbers to a group in the data
file." << endl
<< "There are 50 groups of numbers. The groups of numbers are
displayed to the" << endl
<< "screen - 3 groups per line." << endl << endl;
if(!send2file.fail())//if opening data file was successful


Simply testing send2file in the if statement will suffice as the streams
have an overloaded bool & void* conversion.

if( send2file ) {
...
}

[SNIP]

These are just some comments, though there is certainly room for more
improvement that you can cover yourself, if you want to.

Regards
Chris


Jul 22 '05 #2
I'd suggest that you acquaint yourself with current standard headers
(cstdlib, ctime)

void() - int()

send2file -

been there - done that .... IMHO when programmers desist in presenting
problems that are misleading in their approach to a solution, people
will stop posting the solutions in newsgroups or other bulletin
boards.

And yes the problem is presented as though srand(), rand(), and
time() will be used to produce unique random numbers in a group of 6,
a total of 50 groups, which is in itself extremely misleading. So
when you say no one ever said these functions would produce such an
output, the distinction is not apparent.

This same author in another submission also suggests that an
individual should use a for() loop to present the Fabonacci sequence
of numbers up to a point the loop determines. What the high priestess
of programming forgets to inform everyone of is that this itself is
not possible. She in fact initializes the 1st 2 numbers of the
sequence prior to the loop entry. This must be done regardless of any
language being used. Again extremely misleading.

Why post solutions on the subject?

The question is similar to someone asking instructors that teach
programming at various levels why it is essential for them to receive
texts that have all of the answers readily provided to them, rather
than just using a regular text and doing all of the exercises by
themselves, which is the approach I prefer and take.

This is why such groups exists, people are sincere in their desire
to learn, and periodically request information. It is not that they
are lazy or disingenuous in their efforts. I prefer to help them if
they wish.
More will be posted on another method for generating unique numbers
subsequently.
Jul 22 '05 #3

"August1" <an*********@hotmail.com> wrote in message
news:fc**************************@posting.google.c om...
I'd suggest that you acquaint yourself with current standard headers
(cstdlib, ctime)

void() - int()

send2file -

been there - done that .... IMHO when programmers desist in presenting
problems that are misleading in their approach to a solution, people
will stop posting the solutions in newsgroups or other bulletin
boards.

And yes the problem is presented as though srand(), rand(), and
time() will be used to produce unique random numbers in a group of 6,
a total of 50 groups, which is in itself extremely misleading. So
when you say no one ever said these functions would produce such an
output, the distinction is not apparent.

This same author in another submission also suggests that an
individual should use a for() loop to present the Fabonacci sequence
of numbers up to a point the loop determines. What the high priestess
of programming forgets to inform everyone of is that this itself is
not possible. She in fact initializes the 1st 2 numbers of the
sequence prior to the loop entry. This must be done regardless of any
language being used. Again extremely misleading.

Why post solutions on the subject?

The question is similar to someone asking instructors that teach
programming at various levels why it is essential for them to receive
texts that have all of the answers readily provided to them, rather
than just using a regular text and doing all of the exercises by
themselves, which is the approach I prefer and take.
I perfectly get your point and you might be right that this book (which I
don't know) is crap - there are many of those out there.

This is why such groups exists, people are sincere in their desire
to learn, and periodically request information.
The reason for the existence of this group is to discuss & help people (who
have specific questions!) with standard C++ problems. A group better suited
for what you want might be comp.lang.c++.homework (if it exists?) or
alt.comp.lang.learn.c++
It is not that they
are lazy or disingenuous in their efforts. I prefer to help them if
they wish.
And you should, but let them ask their questions first!
More will be posted on another method for generating unique numbers
subsequently.


Regards
Chris
Jul 22 '05 #4
> And you should, but let them ask their questions first!

The question has already been asked throughout various postings within
this specific newsgroup, therefore a solution was provided and one
that was directed toward introductory level programmers. A more
advanced approach will be posted later when time allows.

Should you demonstrate a similar solution with explanatory
commentation, I'm certain many of the reviewers would be grateful.
Jul 22 '05 #5

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

Similar topics

0
by: August1 | last post by:
This is a follow up to using these functions to produce lottery numbers to an outfile, then read the numbers from the file to the screen. Although other methods are certainly available. ...
4
by: Megan | last post by:
Hi- I need some help/ advise on how to code unique numbers for the primary keys of my 2 tables. I inherited a database that covers information about Hearings and Rulings. Information about the...
1
by: sekitoleko | last post by:
I need some help on representing rational numbers using structures
6
by: Nirjhar Oberoi | last post by:
Hi, Can you add two numbers using a Single Variable? :-) If yes then show me the code!!! Regards Nirjhar
4
by: GeekBoy | last post by:
I am reading a file of numbers using for loops. The numbers are in a grid as follows: 8 36 14 11 31 17 22 23 17 8 9 33 23 32 18 39 23 25 9 38 14 38 4 22 18 11 31 19 16 17 9 32 25 8 1 23
6
by: penny | last post by:
In this assignment we shall look at a possible representation of rational numbers in java using objects. The java language represents rational numbers using the same representation used for other...
3
by: jishara | last post by:
How to write a program in a one page to find the sum of two numbers using php $_POST method.
2
by: lmao29 | last post by:
hi guys, i am new to JAVA I am having trouble with array, anyone can help? here is the problem. if i input 10 numbers, how can i count the unique numbers and output them here is the example: ...
6
by: rahulrhegde | last post by:
Generate 10 digit unique number using VBA ? I used the Unix -Time formula Now the problem with this is 2 person from different computer can generate number at same sec then this will fail...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...

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.