Home >Web Front-end >JS Tutorial >JS implements WeChat red envelope random algorithm (with code)

JS implements WeChat red envelope random algorithm (with code)

php中世界最好的语言
php中世界最好的语言Original
2018-05-15 11:47:164463browse

This time I will bring you JS Implementing the WeChat red envelope random algorithm (with code), what are the precautions for implementing the WeChat red envelope random algorithm with JS, the following is a practical case, one Get up and take a look.

Let’s assume that there is a red envelope of 100 yuan that needs to be sent to 10 people. In order to ensure fairness, the algorithm needs to ensure the following principles:

  • Everyone can grab at least 0.01 yuan

  • Equal opportunities for everyone

  • The sum of everyone’s amounts is equal to 100 yuan

##1. Simple random function implementation

The general idea of ​​​​many friends is:

The first step: Randomly select a number from 0-100 to get the first red envelope amount.

Step 2: Randomly select a number from 0-the remaining amount to get the second red envelope amount.

The third step:...

The last step is to give all the remaining money to the last person.

And so on, get all 10 red envelopes. But I don’t know if you have noticed that this is obviously unfair. The person who grabs it first has an advantage. The first person's random range is 0-100, and he may get a larger amount. The random range of the last person will be very small. If the first person grabs 90 yuan, then the last person has no chance of getting more than 10 yuan. Let’s simulate this process with code:

The test results are as follows:

Careful friends will notice that the balance The value of is incorrect, this is a known issue with

JavaScript floating point operations. Of course, there are many ways to solve it. If you have a good solution, you are welcome to leave me a message.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

vue determines the class usage in the dom

Processes Vue project compilation and deployment in non-website roots Detailed explanation of directory methods

The above is the detailed content of JS implements WeChat red envelope random algorithm (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn