使用沃克别名方法的加权随机选择
本文关键字:加权 随机 选择 方法 别名 | 更新日期: 2023-09-27 18:31:15
我一直在寻找这个算法
(算法将从元素列表中随机选择,其中每个元素具有不同的被选择概率(权重))
并且只找到了 python 和 c 实现,在我做了一个 C# 之后,有点不同(但我认为更简单)我想我应该分享它,我也需要一个 F# 输入,如果有人可以做到,请发布答案
using System;
using System.Collections.Generic;
using System.Linq;
namespace ChuckNorris
{
class Program
{
static void Main(string[] args)
{
var oo = new Dictionary<string, int>
{
{"A",7},
{"B",1},
{"C",9},
{"D",8},
{"E",11},
};
var rnd = new Random();
var pick = rnd.Next(oo.Values.Sum());
var sum = 0;
var res = "";
foreach (var o in oo)
{
sum += o.Value;
if(sum >= pick)
{
res = o.Key;
break;
}
}
Console.WriteLine("result is "+ res);
}
}
}
如果有人可以在 F# 中重新制作它,请发布您的代码
下面是 F# 中的类似代码:
let rng = new System.Random()
let d = [| "A", 3
"B", 2
"C", 3 |]
let sums = Seq.scan (+) 0 (dict d).Values |> Seq.skip 1 |> Seq.toArray
let pick = rng.Next(sums.[sums.Length-1])
let res = fst d.[sums |> Seq.findIndex ((<) pick)]
open System
let oo = dict [ "A", 7;
"B", 1;
"C", 9;
"D", 8;
"E", 11 ]
let rnd = Random()
let pick = oo.Values |> Seq.sum |> rnd.Next
let res = oo |> Seq.scan (fun (_, s) (KeyValue(k, v)) -> k, s + v) ("", 0)
|> Seq.tryPick (fun (k, s) -> if s >= pick
then printfn "Result is %s" k; Some k
else None)