The following column Golang Tutorial will introduce to you how golang implements the double mean algorithm and grabs red envelopes. I hope it will be helpful to friends in need!
Everyone is definitely familiar with grabbing red envelopes, but have you ever thought about how to grab red envelopes?
First of all, we have to clarify the requirements and the constraints of the requirements. There are three main restrictions on red envelopes
a. The total amount grabbed = the total amount of red envelopes, no more or less
b. The minimum value is 0.01 yuan, that is, everyone has a share
c. Everyone grabs The amount of red envelopes received should be averaged as much as possible
Suppose the total amount is M yuan, N people, the amount of each grab = (0, (M/N) *2), for example, still The conditions mentioned before are that the amount is 100 and the number of people is 10.
The amount that the first person grabs is (0,20). According to the normal distribution, the value grabbed should be around 10. The probability of it being much lower than 10 is very high. Small, the sum of the probability is also much greater than 10. It is assumed that the value grabbed by the first person is 10;
The amount grabbed by the second person is (0,90/9 *2)=(0,20) , the same as the first person, the second person’s red envelope amount should also be around 10;
for the remaining people, and so on.
Checked out "Architecture Design of WeChat Red Envelopes", which is the method used. However, this algorithm is not perfect. If the first person grabs 15, the range of the second person is (0,18.89). If the second person grabs a high value, it will be detrimental to the people behind.
Next, let’s take a look at how to implement this double mean algorithm in golang
package mainimport ( "fmt" "math/rand" "time")func main() { //10个人 抢10000分 也就是10个人抢100块钱 count,amount := int64(10),int64(10000) remain := amount sum := int64(0) for i := int64(0);i<count;i++ { x := DoubleAverage(count-i, remain) remain -= x sum += x fmt.Println(i+1,"=",float64(x)/float64(100),", ") } fmt.Println() fmt.Println("总和是:",sum)}//提前定义能抢到的最小金额1分var min int64 = 1//二倍均值算法func DoubleAverage(count,amount int64) int64 { if count == 1 { return amount } //计算出最大可用金额 max := amount - min*count //计算出最大可用平均值 avg := max / count //二倍均值基础上再加上最小金额 防止出现金额为0 avg2 := 2 * avg + min //随机红包金额序列元素,把二倍均值作为随机的最大数 rand.Seed(time.Now().UnixNano()) x := rand.Int63n(avg2) + min return x}
Let’s take a look at the results:
The above is the detailed content of Golang implements the double mean algorithm and the method of grabbing red envelopes. For more information, please follow other related articles on the PHP Chinese website!