using System.Collections;
using System.Collections.Generic;
public static void Main()
var box = new PrizeBox<string>();
foreach (var result in Enumerable.Range(0, 100).Select(x => box.DrawOne()).GroupBy(x => x).Select(x => new
Count = x.Count(), Prize = x.Key
Console.WriteLine(result.Prize+" 出現 "+result.Count+" 次");
public class PrizeBox<T> : ICollection<Prize<T>>
static Random random = new Random();
protected List<Prize<T>> prizeList = new List<Prize<T>>();
protected Prize<T>[] pool;
protected bool boxCalculated = false;
pool = prizeList.Where(x => x.CanDraw && x.Weight > 0 && (!x.MaxTimes.HasValue || x.DrawedTimes < x.MaxTimes.Value)).ToArray();
max = pool.Sum(x => x.Weight);
var getLuckNumber = random.Next(1, max);
foreach (var prize in pool)
getLuckNumber -= prize.Weight;
if (prize.MaxTimes.HasValue && prize.DrawedTimes >= prize.MaxTimes.Value)
throw new Exception("something wrong");
public void Add(T item, int weight, int ? maxTimes = null)
Add(new Prize<T>{Item = item, Weight = weight, MaxTimes = maxTimes});
public void Add(Prize<T> item)
public bool Contains(Prize<T> item)
return prizeList.Contains(item);
public void CopyTo(Prize<T>[] array, int arrayIndex)
prizeList.CopyTo(array, arrayIndex);
public bool Remove(Prize<T> item)
return prizeList.Remove(item);
public IEnumerator<Prize<T>> GetEnumerator()
return prizeList.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
return prizeList.GetEnumerator();