【C#】確率抽選
はい、確率抽選。
必要にかられて作った。
ぼくが知ってるのはもっと長ったらしかった気がするけど、どうせ抽選だしこんなもんでいーべ。
private static Random _rnd = new Random(); public static T WeightedRandom<T>(this IEnumerable<T> source, Func<T, int> selector) { var totalWeight = source.Sum(x => selector(x)); var baseWeight = _rnd.Next(0, totalWeight); var currentWeight = 0; return source.FirstOrDefault(x => { currentWeight += selector(x); return currentWeight > baseWeight; }); }
つかいかた!
var dic = new Dictionary<string, int>() { { "a", 2 }, { "b", 3 }, { "c", 5 } }; var aCount = 0; var bCount = 0; var cCount = 0; foreach (var i in Enumerable.Range(0, 1000000)) { var item = dic.WeightedRandom(x => x.Value); if (item.Key == "a") aCount++; else if (item.Key == "b") bCount++; else if (item.Key == "c") cCount++; } Debug.WriteLine("a:" + aCount.ToString()); Debug.WriteLine("b:" + bCount.ToString()); Debug.WriteLine("c:" + cCount.ToString());
結果!
a:199955
b:299868
c:500177
うん、まぁだいたいあってるし?