Weighted random selection using Walker's Alias Method

后端 未结 2 1053
既然无缘
既然无缘 2020-12-19 20:37


I was looking for this algorithm
(algorithm which will randomly select from a list of elements where each element has different probability of being

2条回答
  •  一向
    一向 (楼主)
    2020-12-19 21:07

    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)
    

提交回复
热议问题