Select a random item from a weighted list

后端 未结 4 449
梦毁少年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 13:57

    The "easiest" way to handle this would be to keep this in a list.

    You could then just use:

    Name GetRandomName(Random random, List names)
    {
        double value = random.NextDouble() * names[names.Count-1].Culmitive;
        return names.Last(name => name.Culmitive <= value);
    }
    

    If speed is a concern, you could store a separate array of just the Culmitive values. With this, you could use Array.BinarySearch to quickly find the appropriate index:

    Name GetRandomName(Random random, List names, double[] culmitiveValues)
    {
        double value = random.NextDouble() * names[names.Count-1].Culmitive;
        int index = Array.BinarySearch(culmitiveValues, value);
        if (index >= 0)
            index = ~index;
    
        return names[index];
    }
    

    Another option, which is probably the most efficient, would be to use something like one of the C5 Generic Collection Library's tree classes. You could then use RangeFrom to find the appropriate name. This has the advantage of not requiring a separate collection

提交回复
热议问题