selection based on percentage weighting

后端 未结 13 2099
忘掉有多难
忘掉有多难 2020-12-04 13:40

I have a set of values, and an associated percentage for each:

a: 70% chance
b: 20% chance
c: 10% chance

I want to select a value (a, b, c) based

13条回答
  •  無奈伤痛
    2020-12-04 14:11

    Here is a complete solution in C#:

    public class ProportionValue
    {
        public double Proportion { get; set; }
        public T Value { get; set; }
    }
    
    public static class ProportionValue
    {
        public static ProportionValue Create(double proportion, T value)
        {
            return new ProportionValue { Proportion = proportion, Value = value };
        }
    
        static Random random = new Random();
        public static T ChooseByRandom(
            this IEnumerable> collection)
        {
            var rnd = random.NextDouble();
            foreach (var item in collection)
            {
                if (rnd < item.Proportion)
                    return item.Value;
                rnd -= item.Proportion;
            }
            throw new InvalidOperationException(
                "The proportions in the collection do not add up to 1.");
        }
    }
    

    Usage:

    var list = new[] {
        ProportionValue.Create(0.7, "a"),
        ProportionValue.Create(0.2, "b"),
        ProportionValue.Create(0.1, "c")
    };
    
    // Outputs "a" with probability 0.7, etc.
    Console.WriteLine(list.ChooseByRandom());
    

提交回复
热议问题