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

'''
我考虑了一个简单的算法:
比如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))

猜你喜欢

转载自blog.csdn.net/caoxinjian423/article/details/112762452
今日推荐