微信红包算法设计-随机红包

本文深入探讨了微信红包算法中随机分配金额的实现原理,通过Python代码解析红包发放过程,包括如何确保每个红包金额均匀且随机,以及如何在有限的总金额和红包个数下保证算法的公平性。
'''
我考虑了一个简单的算法:
比如100元,由10个人分,那么平均一个人是10元钱。然后付款后,系统开始分份儿。
第一份:系统由0~10元之间随机一个数,作为这一份的钱数,设x1。
第二份:剩下的钱(100-x1),系统由0~(100-x1)/(10-1)随机一个数,作为这份的钱数,设x2
.。。。
第n份:剩下的钱(100-x1-x2-...-xn),系统由0~(100-x1-x2-...-xn-1)/(10-n)随机一个数,作为这个份的钱数,设为xn

当用户进来拿红包的时候,系统由0~9之间随机一个数,随机到几,就取第几份红包,然后将这个数存到list里。当之后的用户抽到相同的随机数时,则将这个数+1,如遇相同再+1,直至list满,红包发完。
'''
import random

history_total_money,geted_persons,curr_money = 0,0,0
random_money_list = []
def random_red_envelopes(total_money,total_persons):
    global history_total_money
    global  geted_persons
    global  curr_money
    global  random_money_list
    while geted_persons < total_persons and history_total_money < total_money:
        if geted_persons == 0:
            curr_money = round(random.uniform(0,total_money/total_persons),2)
            history_total_money += curr_money
            random_money_list.append(curr_money)
        elif geted_persons == total_persons-1:
            random_money_list.append(round(total_money - history_total_money))
            break
        else:
            curr_money =  round(random.uniform(0,(total_money-history_total_money)/(total_persons-geted_persons)),2)
            history_total_money += curr_money
            random_money_list.append(curr_money)
        geted_persons += 1
random_red_envelopes(100,10)
print(random_money_list)
for i in range(10):
    j = random.randint(0,9-i)
    print(random_money_list.pop(j))

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值