我必须为抽奖实现一个算法。问题是我希望一些参与者有更多的机会,因为他们有更多的积分。我怎样才能做到这一点?我想简单地把它们放在抽奖中很多次,但似乎不合法。你知道任何可以做到这一点的算法吗?
谢谢
伪算法:
winnerTicket <- a random number between zero and sum ticket count - 1
currentTicket <- 0
For each participant in participants ordered by id
If winnerTicket - currentTicket > participant.ticketCount
currentTicket += participant.ticketCount
Else
return participant
为什么这不是“合法的”。如果您将您的机会数量基于点数,您可以根据他的点数在抽奖中添加该人 X 次。那个人的机率增加。
我会以这种方式解决它。
你有一个映射:participant => number of chances
. 在许多编程语言中,您可以像这样声明映射或字典:
{"player1": 2, "player2": 5, ... many more like these}
所以你可以像这样迭代:
accumulatedMap = {} #an empty map
total = 0
for each pair of key:count in the mapping:
total = total + count
accumulatedMap[key] = total
#now, get random and calculate
element = random between 1 and total, inclusive.
for each pair of key:accumulated in the mapping:
if element <= accumulated:
return key
#at this point, in the worst case the last key was returned.
此代码只是一个示例。请记住,映射在迭代时并不总是保持插入顺序。