Select a random item from a weighted list

后端 未结 4 429
梦毁少年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:09

    Just for fun, and in no way optimal

    List Names = //Load your structure into this
    
    List NameBank = new List();
    foreach(Name name in Names)
       for(int i = 0; i <= (int)(name.Weight*1000); i++)
         NameBank.Add(name.Name)
    

    then:

    String output = NameBank[rand(NameBank.Count)];
    

提交回复
热议问题