我必须为抽奖实施算法。问题是,我希望一些参与者有更多的机会,因为他们有更多的积分。我怎样才能做到这一点? 我只是简单地把它们放在抽奖中,但似乎并不合法。 你知道任何可以做到这一点的算法吗?
由于
答案 0 :(得分:2)
伪算法:
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
答案 1 :(得分:1)
为什么不是“合法的”。如果你的机会数量基于多个点,你可以根据他的积分在抽奖中添加X次。那个人的机会增加了。
我会以这种方式解决它。
答案 2 :(得分:1)
您有一个映射: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.
这段代码只是一个例子。请记住,迭代时,映射并不总是保留一个插入顺序。