简洁的随机红包分配算法

查看 204|回复 21
作者:roy2220   
又到了一年一度刷手气抢红包的时候,假设自己是相关功能开发者,怎么用 python 快速实现随机红包分配?
哈哈,小脑筋转起来,想到一个简单优雅的实现
Here we go:
import random
def generate_red_packets(money_in_cents: int, number_of_red_packets: int) -> list[int]:
    if number_of_red_packets  money_in_cents:
        raise ValueError("too many red packets")
    flags = [0] * (money_in_cents - number_of_red_packets) + [1] * number_of_red_packets
    temp = flags[:-1]
    random.shuffle(temp)
    flags[:-1] = temp
    i = -1
    red_packets = []
    for j, x in enumerate(flags):
        if x == 1:
            # 找到红包
            red_packet = j - i  # 确认红包金额(分)
            red_packets.append(red_packet)
            i = j
    return red_packets
money_in_cents = int(input("总金额(分): "))
number_of_red_packets = int(input("红包个数: "))
red_packets = generate_red_packets(money_in_cents, number_of_red_packets)
print("随机红包列表(分):", red_packets)

int, 红包, flags, temp

good4you   
如果本程序运行在一个 32-bit 的计算机上,有 1 亿元人民币红包要分,它是否能完成任务?
Sawyerhou   
提供个新思路
np.diff(np.pad(np.sort(np.random.randint(1, money - 1, envelopes - 1)),
pad_width=1, mode='constant', constant_values=(0, money)))
Rnreck   
@good4you #1 不太行
roy2220
OP
  
@Sawyerhou 是不是新思路不太清楚,但这样的可读性,面试肯定过不了我这关,哈哈
Sawyerhou   
@roy2220 你不是码农吧?就一行都看不懂,你这连笔试都过不了还面试别人...建议直接跑一下
ericguo   
@roy2220 你要 快速实现 ,人家可是给了你一个,你不是码农吧?
dhja   
当然啊,语言先进了,配置提升了,这种就是基础,没什么好大惊小怪的,个人想法
013231   
@roy2220 你的思路和 Sawyerhou 是一样的,都是生成分割点。但你的实现太丑陋而低效了。
就算不用 numpy ,只用标准库,`generate_red_packets`函数体至少可以写成这样吧:
# Create split points
split_points = random.sample(range(1, money_in_cents), number_of_red_packets - 1)
split_points.sort()
# Calculate diff (amounts of money in each red packet)
split_points = [0] + split_points + [money_in_cents]
return [split_points[i + 1] - split_points[i] for i in range(number_of_red_packets)]
chouqiu   
```php
// 让 ChatGPT 写了个 php 版本的
getMessage();
} catch (Exception $ex) {
// 捕捉并打印其他异常
echo "发生错误: " . $ex->getMessage();
}
```
您需要登录后才可以回帖 登录 | 立即注册

返回顶部