一种未优化但有效的方法是列出所有参赛者,但为参赛者附加与体重成比例的附加索引。
psuedo 完全脱离了任何实际实现的上下文,但你应该明白这一点。
const int DEFAULT_WEIGHT = 1;
public List<Contestant> items = new List<Contestant>();
public List<Guid> LotteryPool = new List<int>();
public Contestant Roll()
{
Random rnd = new Random();
rnd.Seed = DateTime.Now.Ticks;
// Generate LotteryPool
foreach(Contestant item in items)
{
for(int i = 0; i < item.Weight; i++)
{
LotteryPool.Add(item.Id);
}
item.Weight++;
}
// Find the contestant matching a random id from the pool.
Contestant result = FindContestant(LotteryPool[rnd.Next(0, LotterPool.Count]);
// apply the default weight the winner
result.Weight = DEFAULT_WEIGHT;
return result;
}