Generating random numbers without rand() c++

Status
Not open for further replies.

Styler

Beta member
Messages
4
I have an assignment that I must generate 5000 numbers within the range of 1-20. But it states I should use rand() and not srand()..

If I do this I need an if statement to specify that if the number is between 1-20 that it should be written to a file. Doing is to generate 5000 numbers would take very long. Any takes on how to do this faster and memory efficient.
 
I'm not familiar with c++ but I found this :
function
rand
<cstdlib>

int rand ( void );

Generate random number
Returns a pseudo-random integral number in the range 0 to RAND_MAX.

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using srand.

RAND_MAX is a constant defined in <cstdlib>. Its default value may vary between implementations but it is granted to be at least 32767.

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014

Notice though that this modulo operation does not generate a truly uniformly distributed random number in the span (since in most cases lower numbers are slightly more likely), but it is generally a good approximation for short spans.

here :
rand - C++ Reference
so there is no need for "if" .. you can set some value as above to be :
(value % 20 + 1 ) so rang will be 1 to 20

however in this case you will run rand for 5000 times and that is bad any way ..

but there may be another way to have your 5000 numbers ...
- let's say we can get a random number from 1 to 20
- then repeat it random number of times 2 - 8 times is enough !?
- put it in a random place in your file or in a random place in some string or variable then to a file after you get the 5000 number ..

but as I don't know C++ I can't write a code for that !
hope this help .
:)
 
I don't think uniformity is that big of a deal since I think the main goal is them teaching us how to do it uniformily in the end. I will write this program tonight and see how everything works out.
 
Use a for loop to count to the max amount of numbers (5000 in your case), and write them directly to the file instead of using the cout stream.

Code:
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <fstream>

using namespace std;

const int MAX = 5000;

int main()
{
    ofstream outfile;
    outfile.open("data.txt");

    for(int i = 0; i < MAX; i++)
    {
        outfile << rand() % 20 + 1 << endl;
    }

    outfile.close();
    return 0;
}
 
Status
Not open for further replies.
Back
Top Bottom