demo设置了8个奖项,每个奖项可以自定义中奖率,精度为1/10000
public string PrizeDraw()
{
//奖品以及中奖率
const string prizeString = "奖品一:33,奖品二:30,奖品三:9,奖品四:8,奖品五:7,奖品六:6,奖品七:5,奖品八:2";
//将中奖率*100再取整,放在数组中,并从小到大排序
var prizeArray = prizeString.Split(',').Select(j => new { Prize = j.Split(':')[], Change = (int)(double.Parse(j.Split(':')[])* ) }).OrderBy(j => j.Change).ToArray();
//将中奖率累加,放到字典里
var prizeDictionary = new Dictionary<string, int>();
for (var i = ; i < ; i++)
{
var allChange = ;
for (var j = ; j <= i; j++)
{
allChange += prizeArray[j].Change;
}
prizeDictionary.Add(prizeArray[i].Prize, allChange);
}
//产生一个1-10000的随机数
var rd = new Random();
var rdChange = rd.Next(, );
//找第一个大于随机值的奖项
return prizeDictionary.First(j => j.Value >= rdChange).Key;
}