Select x random elements from a weighted list in C# (without replacement)

前端 未结 4 848
旧巷少年郎
旧巷少年郎 2020-12-19 10:00

Update: my problem has been solved, I updated the code source in my question to match with Jason\'s answer. Note that rikitikitik answer is solving the issu

4条回答
  •  悲哀的现实
    2020-12-19 10:15

    You could do this:

    Card GetCard(List cards)
    {
      int total = 0;
      foreach (Card c in cards)
      {
        total += AttributionRate;
      }
    
      int index = Random.Next(0, total - 1);
      foreach(Card c in cards)
      {
        index -= c.AttributionRate;
        if (index < 0)
        {
          return c;
        }
      }
    }
    
    Card PopCard(List cards)
    {
      Card c = GetCard(cards);
      cards.Remove(c);
    }
    

    In theory this should work.

提交回复
热议问题