0%

微信红包算法

用python实现的微信红包算法,有些地方还是没有搞明白,如果有人知道还请指教

算法精要

主要在于随机数的生成

1
2
3
4
#这一句是重点,不知道为什么
#如果比2.0小则前面的红包是小,后面大
#如果比2.0大则前面是大红包,后面是小红包
max = remainAmount / remainSize * 2.0

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#! encoding:utf-8

import random

import math


def getMoney(remainAmount,remainSize):
if remainSize == 1:
money = round(remainAmount * 100) / 100
else:
min = 0.01
#这一句是重点,不知道为什么
#如果比2.0小则前面的红包是小,后面大
#如果比2.0大则前面是大红包,后面是小红包
max = remainAmount / remainSize * 2.0
#print remainAmount,remainSize,max

money = random.random() * max
money = money <= min and min or money
money = math.floor(money * 100) / 100;

return money

#模拟发放
def simulateRedPacket(amount,num):
remainSize = num
remainAmount = amount

#初始化数组
results = [0 for x in xrange(0,num)]

#模拟发红包
for x in xrange(0,num):
money = getMoney(remainAmount,remainSize)
remainSize -= 1
remainAmount -= money
results[x] = money


#计算发放总额
sum = 0
for x in results:
sum += x

if amount - sum > 0.01:
#发放结果
pass
print results
print ", ".join([" = ".join(["金额",str(amount)])," = ".join(["数量",str(num)])," = ".join(["已发放",str(sum)])," = ".join(["差额",str(amount - sum)])])

if __name__ == '__main__':
for x in xrange(1,2000):
#金额
amount = round(random.random() * 100) * 1000 / 100
#红包数量
num = random.randint(1,100)

simulateRedPacket(amount,num)