Random number generation

I use the code below to generate random numbers in a range ...

int randomNumberWithinRange(int min,int max) { int snowSize = 0; do { snowSize = rand()%max; } while( snowSize < min || snowSize > max ); return snowSize; } for(int i = 0; i < 10 ; i++) NSlog("@"%d",\t", randomNumberWithinRange(1,100)); 

If I left my application and restarted, the same set of numbers will be created. How to create a different set of random numbers for each run.

+4
source share
6 answers

Do something like e.g. srand(time(NULL)) , i.e. synchronize it with time (in the initialization of your program, of course).

+11
source

You must initialize the seed random number generator as indicated.

In addition, you should avoid a loop:

 int randomNumberWithinRange(int min,int max) { return min + rand() % (max - min + 1); } 
+4
source

You need to plant a random number generator.

On the man page:

The srand () function uses the argument as the seed for a new sequence of pseudorandom numbers to be returned by subsequent calls to rand (). If srand () is then called with the same initial value, the sequence of pseudo random numbers must be repeated. If rand () is called before any calls to srand () are made, the same sequence should be generated as when srand () was first called using an initial value of 1.

+3
source

You should use arc4random instead of rand , for many reasons, one of which arc4random does not require seeding.

+3
source

This code generates a unique random number only once.

 #include <ctime> # include <iostream> using namespace std; int main() { int size=100; int random_once[100]; srand(time(0)); for (int i=0;i<size;i++) // generate unique random number only once { random_once[i]=rand() % size; for(int j=0;j<i;j++) if (random_once[j]==random_once[i]) i--; } for ( i=0;i<size;i++) cout<<" "<<random_once[i]<<"\t"; return 0; 
0
source

In addition to sowing a random number generator using srand (), your general technique is not entirely correct here. First of all, you should never use a module to cut the range of rand. These are the least significant bits of users, which are less random. Secondly, there is no need for a loop. You can get the range directly. Here's how to do it:

snowSize = min + (int) (max * (rand () / (RAND_MAX + 1.0)));

-1
source

Source: https://habr.com/ru/post/1307786/


All Articles