对于我的程序,我已经提示用户将20个名称放入一个数组(数组大小为5,现在进行测试),然后将该数组发送到文本文档。我需要这样做,它将从列表中随机选择一个名称并显示它(我已经完成了)。但我现在需要增加一个名字被选中的机会,我该怎么做呢?
EG。我希望增加从阵列中挑选“Jim”这个名字的机会。
class Programt
{
static void readFile()
{
}
static void Main(string[] args)
{
string winner;
string file = @"C:\names.txt";
string[] classNames = new string[5];
Random RandString = new Random();
Console.ForegroundColor = ConsoleColor.White;
if (File.Exists(file))
{
Console.WriteLine("Names in the text document are: ");
foreach (var displayFile in File.ReadAllLines(file))
Console.WriteLine(displayFile);
Console.ReadKey();
}
else
{
Console.WriteLine("Please enter 5 names:");
for (int i = 0; i < 5; i++)
classNames[i] = Console.ReadLine();
File.Create(file).Close();
File.WriteAllLines(file, classNames);
Console.WriteLine("Writing names to file...");
winner = classNames[RandString.Next(0, classNames.Length)];
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\nThe winner of the randomiser is: {0} Congratulations! ", winner);
Thread.Sleep(3000);
Console.Write("Completed");
Thread.Sleep(1000);
}
}
}
答案 0 :(得分:0)
有两种方法可以做到这一点。您可以生成具有针对一个数字的正态分布的RNG。
或者更简单的方法是翻译步骤。在0-100范围内生成,然后生成代码,以有偏见的方式转换为答案,例如
这有80%的机会选择答案3,其他人只有5%的机会
因此,您目前拥有RandString.Next(0, classNames.Length)
的位置可以使用类似GetBiasedIndex(0, classNames.Length, 3)
该函数看起来像这样(带有测试代码):
public Form1()
{
InitializeComponent();
int[] results = new int[5];
Random RandString = new Random();
for (int i = 0; i < 1000; i++)
{
var output = GetBiasedIndex(RandString, 0, 4, 3);
results[output]++;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 5; i++)
{
builder.AppendLine(results[i].ToString());
}
label1.Text = builder.ToString();
}
private int GetBiasedIndex(Random rng, int start, int end, int target)
{
//Number between 0 and 100 (Helps to think percentage)
var check = rng.Next(0, 100);
//There's a few ways to do this next bit, but I'll try to keep it simple
//Allocate x% to the target and split the remaining y% among all the others
int x = 80;//80% chance of target
int remaining = 100 - x;//20% chance of something else
//Take the check for the target out of the last x% (we can take it out of any x% chunk but this makes it simpler
if (check > (100 - x))
{
return target;
}
else
{
//20% left if there's 4 names remaining that's 5% each
var perOther = (100 - x) / ((end - start) - 1);
//result is now in the range 0..4
var result = check / perOther;
//avoid hitting the target in this section
if (result >= target)
{
//adjust the index we are returning since we have already accounted for the target
result++;
}
//return the index;
return result;
}
}
和输出:
52
68个
55个
786个
39
如果您要重复调用此函数,则需要传入RNG的实例,这样您就不会在每次调用时重置种子。
如果您想要定位名称而不是索引,您只需先查找该名称,并在找不到该名称时设置其他条件