Home > Web Front-end > JS Tutorial > How to use JS to implement WeChat red envelope algorithm

How to use JS to implement WeChat red envelope algorithm

php中世界最好的语言
Release: 2018-06-02 10:17:52
Original
1871 people have browsed it

This time I will show you how to use JS to implement the WeChat red envelope algorithm, and what are the precautions for using JS to implement the WeChat red envelope algorithm. The following is a practical case. Let’s 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 functionimplementation

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:

How to use filter in vue

##How to use vue to determine the class of dom

The above is the detailed content of How to use JS to implement WeChat red envelope algorithm. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template