Random Number Generation Conversion-generate a random number within () according to the random number generator

Source: Internet
Author: User

1. Question

Given a random number generator, this generator can generate a random number ranging from 1 to 5 () evenly. How can we use this generator to generate a number ranging from 1 to 7?

2. Ideas

Method 1: generate two (1, 5) random numbers. In this case, there are 25 random numbers. Note that these two numbers are sequential. In these 25 cases, take the first 21 random numbers, each three represents a number in (). If you get a number other than these 21 types, you can discard them.

Method 2: generate three () random numbers, representing a binary bit, where 1 and 2 map to 0, 3 Skip, 4 and 5 map to 1. The resulting three-digit binary number, that is, the 8 numbers 1-8 are of equal probability. If 8 is generated, discard it.

Method 3: generate two (1, 5) random numbers, and generate a binary number, 5*(random5 ()-1) + random5 (). This formula can produce 1-25 equi-probability, that is, the first random number represents:, 20, and the position represents 1, 2, 3, 4, 5. In this way, this number (a number ranging from 1 to 25) is discarded by using the method 1 with only 1-21 and 7 points, representing 1-7, 22-25.

3. Reference

Generate a random number within () according to the random number generator ().
[Beauty of programming] Summary of random number range extension methods

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.