如何根据百分比随机选择

时间:2015-11-24 08:23:30

标签: c#

我有一堆物品,大小从1-10到不等。

我想根据对象的大小或概率来确定项目的大小。

例如:

项目大小为1的几率= 50%几率

物品大小为5的概率= 20%几率

物品大小10的几率= 5%几率

我知道我当然需要使用随机发生器。

但只是想知道你们中的一些人会怎样在C#中解释这个逻辑?

2 个答案:

答案 0 :(得分:5)

首先:提供的概率不能达到100%

  50% + 20% + 5% = 75%

所以你必须检查这些值。您可能希望生成这些每分钱:

  // Simplest, but not thread safe
  private static Random s_Random = new Random();

  ...

  int perCent = s_Random.Next(0, 100);

  if (perCent < 50) {               //  0 .. 49
    // return Item of size 1
  }
  else if (perCent < 50 + 20) {     // 50 .. 69
    // return Item of size 5
  }
  else if (perCent < 50 + 20 + 5) { // 70 .. 74 
    // return Item of size 10
  } 
  ...

答案 1 :(得分:3)

使用我的方法。它简单易懂。 我不计算0 ... 1范围内的部分,我只使用&#34; Probabilityp Pool&#34; (听起来很酷,是吗?) 我列出了我想要选择的所有元素。每个元素都有自己的机会。设置最常见的元素几率为100是有用的,因此大多数稀有元素将是60或50。

At circle diagram you can see weight of every element in pool

Here you can see an implementing of accumulative probability for roulette

`

// Some c`lass or struct for represent items you want to roulette
public class Item
{
    public string name; // not only string, any type of data
    public int chance;  // chance of getting this Item
}

public class ProportionalWheelSelection
{
    public static Random rnd = new Random();

    // Static method for using from anywhere. You can make its overload for accepting not only List, but arrays also: 
    // public static Item SelectItem (Item[] items)...
    public static Item SelectItem(List<Item> items)
    {
        // Calculate the summa of all portions.
        int poolSize = 0;
        for (int i = 0; i < items.Count; i++)
        {
            poolSize += items[i].chance;
        }

        // Get a random integer from 0 to PoolSize.
        int randomNumber = rnd.Next(0, poolSize) + 1;

        // Detect the item, which corresponds to current random number.
        int accumulatedProbability = 0;
        for (int i = 0; i < items.Count; i++)
        {
            accumulatedProbability += items[i].chance;
            if (randomNumber <= accumulatedProbability)
                return items[i];
        }
        return null;    // this code will never come while you use this programm right :)
    }
}

// Example of using somewhere in your program:
        static void Main(string[] args)
        {
            List<Item> items = new List<Item>();
            items.Add(new Item() { name = "Anna", chance = 100});
            items.Add(new Item() { name = "Alex", chance = 125});
            items.Add(new Item() { name = "Dog", chance = 50});
            items.Add(new Item() { name = "Cat", chance = 35});

            Item newItem = ProportionalWheelSelection.SelectItem(items);
        }