Pseudorandom number generator.

Revision en3, by Rajan_sust, 2018-04-09 05:59:08

Question 01:

Is there any technique where generating random number within a range is equiprobable ?

Question 02:

What is the extra advantage of the following method 02 and method 03 ?

srand(time(NULL);

//Method 01: general approach

int myrand(int mod){
  return rand()%mod;
}

//Method 02: Taken form red coder submission.

int myrand(int mod) {
    int t = rand() % mod;
    t = (1LL*t*RAND_MAX + rand()) % mod;
    return t;
}

//Method 03: Also Taken from red coder submission.

int myrand(int mod) {
	return (int) ( (((double) rand() / RAND_MAX) * (mod) ));
}

Updated : Idea from diko.

auto seed = auto seed = chrono::high_resolution_clock::now().time_since_epoch().count();
std::mt19937 mt(seed);

int myrand(int mod) {
    return mt()%mod;
}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English Rajan_sust 2018-07-24 16:31:22 12 Tiny change: 'to seed = auto seed = ' -> 'to seed = '
en4 English Rajan_sust 2018-04-18 13:30:50 164
en3 English Rajan_sust 2018-04-09 05:59:08 30
en2 English Rajan_sust 2018-04-08 04:55:58 229 Tiny change: '~~\n\n\n\nIdea from ' -> '~~\n\n\n\n**Updated** : Idea from '
en1 English Rajan_sust 2018-04-07 09:27:21 657 Initial revision (published)