Generate Random Weighted value

前端 未结 6 1461
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 10:19

Edit: I\'ve rewritten the question in hopes that the goal is a little clearer.

This is an extended question to this question here, and I really like

6条回答
  •  醉酒成梦
    2020-12-28 10:39

    Quick and dirty way in C#:

    T PickWeightedRandom(IEnumerable> items, Random r)
    {
        var sum = 0.0;
        var rand = r.NextDouble();
        return items.First(x => { sum += x.Item2; return rand < sum; }).Item1;
    }
    

    Test code:

    var values = new [] { 
        Tuple.Create(1, 0.05),
        Tuple.Create(2, 0.15),
        Tuple.Create(3, 0.3),
        Tuple.Create(4, 0.3),
        Tuple.Create(5, 0.15),
        Tuple.Create(6, 0.05),
    };
    
    const int iterations = 1000;
    
    var counts = new int[values.Length];
    var random = new Random();
    
    for (int i = 0; i < iterations; i++)
    {
        counts[PickWeightedRandom(values, random)-1]++;
    }
    
    foreach (var item in counts)
    {
        Console.WriteLine(item/(double)iterations);
    }
    

    Output (with iterations = 1000000):

    0.050224
    0.150137
    0.300592
    0.298879
    0.150441
    0.049727
    

    Looks like:

提交回复
热议问题