这是我对“加权随机”的理解,我最近一直在使用它。 (代码在 Python 中,但可以用其他语言实现)
假设您想随机选择一个人,但他们被选中的机会并不相同
您可以给每个人一个“权重”或“机会”值:
choices = [("Ade", 60), ("Tope", 50), ("Maryamu", 30)]
您使用他们的权重计算每个分数,然后找到得分最高的选项
highest = [None, 0]
for p in choices:
score = math.floor(random.random() * p[1])
if score > highest[1]:
highest[0] = p
highest[1] = score
print(highest)
对于 Ade,他们可以获得的最高分是 60,Tope 50 等等,这意味着 Ade 比其他人更有可能获得最高分。
您可以使用任何范围的权重,差异越大,分布越偏斜。
例如,如果 Ade 的权重为 1000,那么他们几乎总是会被选中。
测试
votes = [{"name": "Ade", "votes": 0}, {"name": "Tope", "votes": 0}, {"name": "Maryamu", "votes": 0]
for v in range(100):
highest = [None, 0]
for p in choices:
score = math.floor(random.random() * p[1])
if score > highest[1]:
highest[0] = p
highest[1] = score
candidate = choices(index(highest[0])) # get index of person
votes[candidate]["count"] += 1 # increase vote count
print(votes)
// votes printed at the end. your results might be different
[{"name": "Ade", "votes": 45}, {"name": "Tope", "votes": 30}, {"name": "Maryamu", "votes": 25}]
问题
看起来选民越多,结果就越容易预测。哎呀
希望这能给某人一个想法......