4


我一直在寻找这种算法
(该算法将从元素列表中随机选择,其中每个元素具有不同的被挑选概率(权重))
,并且在我做了一个 C# 之后,只发现了 python 和 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# 中重新制作它,请发布您的代码

4

2 回答 2

6

这是 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)]
于 2012-04-15T17:57:50.870 回答
5
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)
于 2012-04-15T18:07:02.800 回答