Search code examples
c++randomrandom-seedsrand

C++ generate random numbers for a given seed


I need to create a random number generator that generates n random numbers for a given seed s. k largest or smallest values generated are also known.

ex1 :

Seed (s): 123

No of random numbers (n):100

largest 10 random numbers sorted: 7523372 29439913 58320284 86168869 91064068 92596215 95168426 128959393 150074451 246577027

ex2 :

Seed (s): 12345

No of random numbers (n):1000000

smallest 50 random numbers largest to smallest: 2147483534 2147483066 2147478401 2147475092 2147470457 2147463295 2147460100 2147455072 2147454293 2147453287 2147450344 2147449403 2147448482 2147446509 2147444055 2147443731 2147443589 2147442701 2147436885 2147434035 2147429273 2147427145 2147426476 2147423920 2147417804 2147414079 2147407803 2147407048 2147386660 2147382475 2147381554 2147373468 2147372380 2147367051 2147366858 2147365895 2147358392 2147355655 2147344012 2147338974 2147338218 2147331959 2147312904 2147311693 2147288461 2147277290 2147265613 2147244881 2147175859 2147145872

But the random number generator I have code is not generating the required random numbers.

For ex1 :

The random numbers generated are 440 19053 23075 13104 32363 3265 30749 32678 9760 28064 20429 750 4480 3863 30429 18586 30758 31595 31567 24630 16059 2734 703 3966 12383 18065 28392 29902 26443 16505 11114 11737 10421 3541 2251 22174 14324 24238 18619 29848 25829 25215 16284 8757 22925 28488 12097 3722 27392 7902 16118 9541 29057 22149 13505 29411 27626 27840 21480 6435 29263 24936 1203 26554 15326 23548 10611 27976 15369 25656 17603 5259 6888 2281 21774 8658 3288 26879 2386 9397 19817 21220 13091 12804 16759 28172 6642 31229 1174 8910 5007 3778 26036 13426 1517 28426 5881 16779 13862 10518

which doesnt have any of the largest 10 numbers given.

Below is the code I have now.

int main(int argc, char* argv[]) {

    srand(123);

    //int range = 2147483647  + 1;

    int num;
    for (int j = 0; j < 100; j++) {
       num = rand();// % range ;
       cout << num << endl;
}
return 0;
}

How can I fix this?


Solution

  • According to the documentation (which you really should read!):

    Returns a pseudo-random integral value between ​0​ and RAND_MAX

    Where RAND_MAX is implementation defined, but is guaranteed to be at least 32767. In fact, it often is 32767, and that appears to apply to you.

    The documentation also states:

    rand() is not recommended for serious random-number generation needs. It is recommended to use C++11's random number generation facilities to replace rand().

    And that is what I would advise you to do.

    But as for getting specific output, that's another thing. It's a strange requirement, where is it coming from?