Complete example of weight random algorithm implemented in Java language

preface

Now apps are springing up, whizzing out. Experienced, inexperienced, qualified and unqualified people want to start a business. More than 90% of entrepreneurs need to make an app, which seems to have become the standard configuration for entrepreneurship.

If you make an app, you have to promote it. How to push it? Issuing coupons and giving money is the most important. Now many products or operations require that the amount of coupons can be given randomly, but it can't be too random. Are the coupons given money, investors' money, right.

Therefore, in the randomly generated amount, it is required that the probability of small amount should be large and the probability of large amount should be small. For example, 70% of 3 yuan, 25% of 5 yuan and 5% of 10 yuan are required to generate coupons. What should we do?

For the above problems, directly use our random next(Integer range); Not enough. Because this pseudo-random has no weight, the probability of 3, 5 and 10 is the same.

Realization idea

Let's take the above example. The probability of 3 is 70%, we assign its weight to 70, the probability of 5 is 25%, we assign its weight to 25, the probability of 10 is 5%, and we assign its weight to 5

We calculate the weight summation in order, take the value before the weight summation of the current number as the starting value of its weight range, and take the value after the summation as the end value of its weight range.

In this way, we can use random Next (100) to make a random number, then judge the range where the random number falls, and then map it to the corresponding coupon value.

Java implementation

result:

Implementation of dichotomy

Let's share another example to strengthen the understanding of the weight random algorithm and put it in place at one time!

The weight random algorithm is widely used in lottery, resource scheduling and other systems. A simple random implementation is based on the weight. The weight is the proportion of hits of several random objects (classification). The higher the weight setting, the easier the life is, and the sum can not be equal to 100;

The simple implementation code is as follows:

result:

summary

The above is all about the complete example of weight random algorithm implemented in Java language. I hope it will be helpful to you. If there are deficiencies, please leave a message to point out. Thank you for your support!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>