Select a random item from a weighted list

后端 未结 4 443
梦毁少年i
梦毁少年i 2020-12-10 13:30

I am trying to write a program to select a random name from the US Census last name list. The list format is

Name           Weight Cumulative line
-----              


        
4条回答
  •  抹茶落季
    2020-12-10 14:03

    I've created a C# library for randomly selected weighted items.

    • It implements both the tree-selection and walker alias method algorithms, to give the best performance for all use-cases.
    • It is unit-tested and optimized.
    • It has LINQ support.
    • It's free and open-source, licensed under the MIT license.

    Some example code:

    IWeightedRandomizer randomizer = new DynamicWeightedRandomizer();
    randomizer["Joe"] = 1;
    randomizer["Ryan"] = 2;
    randomizer["Jason"] = 2;
    
    string name1 = randomizer.RandomWithReplacement();
    //name1 has a 20% chance of being "Joe", 40% of "Ryan", 40% of "Jason"
    
    string name2 = randomizer.RandomWithRemoval();
    //Same as above, except whichever one was chosen has been removed from the list.
    

提交回复
热议问题