Home  >  Article  >  Web Front-end  >  How to use JS to create WeChat red envelope algorithm

How to use JS to create WeChat red envelope algorithm

php中世界最好的语言
php中世界最好的语言Original
2018-06-06 09:38:121725browse

This time I will show you how to use JS to make the WeChat red envelope algorithm, and what are the precautions for using JS to make the WeChat red envelope algorithm. The following is a practical case, let's take a look. z

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:

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

Recommended reading:

How to operate vue-cli2.9.3

How the WeChat applet should be laid out

The above is the detailed content of How to use JS to create WeChat red envelope algorithm. 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