Randomly generate m integers between [s, e]

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.