Weighted random selection using Walker's Alias Method (c# implementation)

Posted by Chuck Norris on Stack Overflow See other posts from Stack Overflow or by Chuck Norris
Published on 2012-04-15T17:23:42Z Indexed on 2012/04/15 17:30 UTC
Read the original article Hit count: 803

Filed under:
|
|
|


I was looking for this algorithm
(algorithm which will randomly select from a list of elements where each element has different probability of being picked (weight) )
and found only python and c implementations, after I did a C# one, a bit different (but I think simpler) I thought I should share it, and ask your opinion ?
this is it:

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);
        }
    }
}

if anyone can remake it in f# please post your code

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET