Search code examples
c++file-iorandomifstream

Can't Generate Full Range of Random for Integers


I am trying to generate a file of 10000 integers between 0 and 100 000 so I can do a MergeSort on them later.

When I generate the file using fstream, I never get an integer over 32760.

The following method generates the file and then reads it back and checks for any integer over 32750. I usually get between 3-5 integers between 32750 and 32760. Why does this happen and how can I fix it? Is it a seed problem or the actual use of the Random function?

// sizeOfArray = 10000
void generateFile() {
    ofstream fout("unsorted.txt");
    srand(time(NULL));

    // Generating the file
    int num;
    for(int i = 0; i < sizeOfArray; i++) {
         num = rand() % 100000;
         if(i < sizeOfArray-1)
            //fout << i+1 << ": " << num << endl;
            fout << num << endl;
         else
            //fout << i+1 << ": " << num;
            fout << num;
    }

    // Reading the File Back
    ifstream fin("unsorted.txt");
    for(int i = 0; i < sizeOfArray; i++) {
        fin >> num;
        if(num > 32750)
            cout << num << endl;
    }

    cin.get();
}

SOLVED
Using the answer provided below I generated the file 500 times
and the highest Integer I received was 99931.


Solution

  • The highest random value that you can get from rand() is RAND_MAX, a library-dependent constant. In your case, it appears to be set to 2^15-1, the highest positive number that fits in a signed 16-bit integer.

    When you need to generate numbers that are larger than RAND_MAX, call rand() several times, each time multiplying by RAND_MAX. For example, in your case the following code should work (I am assuming that your int has 32 bits):

    num = rand();
    num *= RAND_MAX;
    num += rand();
    num %= 100000;
    

    Note that merely adding three random numbers together to get the desired range will not produce the same random distribution as multiply and add approach.