Randomly generate m integers that are different from each other in [s, e ].
Consider this: Take the number of m from n (e-s + 1) integers, then the probability of each number is m/n.
How can this be applied?
This can be used to randomly generate an integer between [1, n]. If the number is smaller than or equal to m, it indicates that the probability of m/n is satisfied, that is, the probability m/n event occurs.
The proof of mathematics is probably complicated ~~~
The code is implemented as follows:
// Randomly generate m numbers between [s, e] and store them in p [] void GetRandomNum (int * p, int s, int e, int m) {assert (p); int k = 0; srand (time (NULL); for (int I = s; I <= e & m; I ++) {// rand () % (e-I + 2): randomly generate a [1, integer if (1 + rand () % (e-I + 2) <= m) {p [k ++] = I; // printf ("% d \ n", I); m --;}}}
Another problem: random generation and N integers for S
There are multiple ways to solve this problem. The projection method uses the above algorithm.
Suppose we want to generate a sum of six numbers for 15, and use GetRandomNum to obtain 5 numbers: 1, 3, 6, 8, and 14. For example, we identify these six numbers on the number axis.
We can see that OA + AB + BC + CD + DE + EF must be equal to 15. The sum of their lengths is
1, 2, 3, 2, 6, 1
This shows a combination: 1 + 2 + 3 + 2 + 6 + 1 = 15
Conclusion: 1 randomly generates the N-1 integers between [1, S), and then add S to Form N integers. 2. Find the difference between them in order.