字符串数组,增加某个字符串被选中的几率
本文关键字:字符串 几率 数组 增加 | 更新日期: 2023-09-27 18:21:44
我对这整件事还很陌生。我正在制作一个程序,它会提示用户输入一个名称,然后将这个名称存储在一个数组中(数组大小为4),然后随机选择一个名称并显示它。
我想知道如何增加某个名字被选中的机会,例如,我输入上下快速移动Jim,约翰,Tim,进入阵列后,Bob被选中的机会会增加吗?我不知道从哪里开始,甚至不知道该做什么,我到处找。
这个选项相当简单。
- 生成包含名称权重的简单类
- 初始化一个所有名称及其权重的列表(由您定义权重)
- 对于每个名称,根据其X权重将其添加到主数组中
- 随机获取一个介于0和数组上限之间的索引
public class NameOption
{
public string Name { get; set; }
public int Weight { get; set; }
public NameOption(string name, int weight)
{
Name = name;
Weight = weight;
}
}
// Will need the System.Linq namespace declared in order to use the LINQ statements
public string PickName()
{
var nameOptions = new List<NameOption>
{
new NameOption("Bob",5),
new NameOption("John", 1),
etc...
};
// FYI - following won't work if Weight was a negative value or 0.
var namesToPickFrom = new string[nameOptions.Sum(x => x.Weight)];
var nameIndex = 0;
foreach (var option in nameOptions)
{
for (var i = 0; i < option.Weight; i++)
namesToPickFrom[nameIndex++] = option.Name;
}
var random = new Random();
return namesToPickFrom[random.Next(0, namesToPickFrom.Length-1)];
}
简单---作弊。
与其选择一个数字(0-3),不如选择一个(0-4),如果你得到4,就用0。
您还没有进行足够的搜索,因为这很容易,也是一个众所周知的概率问题。为了尽可能简单,只需使用两个数组,一个带有名称,另一个带有正整数。
整数有什么值并不重要,只要它们表示被拾取的权重即可。这是概率的相对度量。
现在求和:
i = 0;
sum = 0;
while (i < prob.Length)
{
sum += prob[i];
}
pick = rnd.Next(sum); // 0..sum-1
i = 0;
while (pick >= prob[i])
{
pick -= prob[i];
i++;
}
// i is now the index of the name picked
对于每个名称存储,它将被拾取的百分比。确保百分比加起来为100。根据百分比为每个名称指定范围。
伪示例:
Bob = 50%
Jim = 10%
John = 20%
Tim = 20%
//Have your code assign Ranges Based on the percentage:
Bob: Low=1, High=50
Jim: Low=51, High=60
John: Low=61, High=80
Tim: Low=81, High=100
//Get a random number between 1 and 100. Use if-elses to return the matching name.