I. Concepts
1. The C ++ standard function library provides a random number generator Rand, which returns a pseudo random integer evenly distributed between 0 and rand_max. Rand_max must be 32767 at least. The rand () function does not accept parameters. The default value is 1 (the start value ). The random number generator always starts with the same seed, so the pseudo-random sequence is also the same, without the random meaning.
2. In C ++, another function srand () can specify different numbers (unsigned integer yuan) as seeds. However, if the seeds are the same, the pseudo-random sequence is also the same. One way is to let the user input seeds, but it is still not ideal.
3. It is ideal to use a variable number, such as time, as the seed of the random number generator. The value of time varies every moment. So the seeds are different, so the random numbers are also different.
4. c ++ Random Functions
Srand (unsigned) Time (null); // The srand () function generates a Random Seed starting from the current time
For (INT I = 0; I <10; I ++)
Cout <rand () % max <Endl; // Max is the maximum value, and its random field is 0 ~ MAX-1
2. Set the probability as required
For example, to set a 10% probability problem, we can use the rand () function to implement it. In the if condition sentence judgment, we can use the rand () Value % A set value, then perform the "=" operation with another value.
For example:
If (1 = rand ())
// A probability of 10% is achieved.
Else
// The probability of 90% is not reached
Iii. Simple algorithms for random numbers
1. Generate a random number in the specified range.
Generally, we can use j = 1 + (INT) (N * rand ()/(rand_max + 1.0) to generate a random number between 0 and N.
If int x = rand () % 101; is used to generate a random number between 0 and 100, this method is not advisable. A good practice is:
J = (INT) (100.0 * rand ()/(rand_max + 1.0 ))
2. for a screening random number, if you want to obtain a random number ranging from 0 to 99, it cannot be 6.
Solution:
X = random (1, 100 );
While (x = 6)
{
X = random (1, 100 );
}
Another example is to use a random number ranging from 0 to 99, but not a multiple of 5. solution:
X = random (1, 100 );
While (X % 5) = 0 ){
X = random (1, 100 );
}
Iv. Lua's instant function, which can be directly used in cocos2d_x + Lua
Math. randomseed (OS. Time () is equivalent to the srand () process.
I = math. Random () generates a random number between 1 and 6.