我有一大堆的项目比范围的大小从1-10。
我想根据物件的百分比或机会确定该物件的大小。
例如:
物品成为大小的 机会1 = 50% 机会
物品成为大小的 机会5 = 20% 机会
物品成为大小的 机会10 = 5% 机会
我知道我当然需要为此使用Random发电机。
但是只是想知道你们中的某些人将如何使用C#进行逻辑处理?
小智 8
用我的方法。它简单易懂。我不计算 0...1 范围内的部分,我只使用“Probabilityp Pool”(听起来很酷,是吗?)我列出了我想要选择的所有元素。每个元素都有自己的机会。设置最常见元素机会 = 100 很有用,因此最稀有元素将是 60 或 50。
`
// 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);
}
Run Code Online (Sandbox Code Playgroud)
首先:所提供的概率之和不等于100%:
50% + 20% + 5% = 75%
Run Code Online (Sandbox Code Playgroud)
因此,您必须检查这些值。您可能希望产生以下百分比:
// 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
}
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8900 次 |
| 最近记录: |