bIG*_*_aL 5 c# arrays random for-loop tostring
我在C#中有一个彩票应用程序,其中包含要绘制的数字的数量以及要绘制的最大数量.我已编码为创建一个包含所需随机数的数组但我需要它们是唯一的并且我很难做到这一点如果有人能给我一些建议,我将非常感激,谢谢
到目前为止,这是我的代码:
class Lottery
{
static int[] numberHolder; //array to be filled with numbers up to an
//amount entered by the user eg 42 Max
static int[] drawHolder; //array to hold the each random number
//drawn from the pool of numbers eg 7 numbers
public Lottery() //Lottery class Constructor
{
}
//method which takes in a number limit and amount of numbers to be drawn
public String drawNumbers(int numLimit, int numAmount)
{
Random RandomNumber = new Random();
for (int i = 0; i < numLimit ; i++) //loop to fill up numberHolder array
// with predefined limit of numbers
{
numberHolder[i] = i++;
}
for (int i = 0; i < numAmount; i++)
{
// code to pick unique random numbers no greater than numAmount
// and add them to the drawHolder[] array
drawHolder[i] = RandomNumber.Next(1, numLimit);
}
//return the drawHolder array to String
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
在我看来,你应该改变你的方法.
而不是想"我将生成随机索引来选择我的数字",你必须确保你没有得到任何重复项,我只是将数组洗牌并首先取得你需要的X. 这样,您无需担心索引或重复项.
所以你的第二个for循环将改为
drawHolder = numberHolder.OrderBy(x => new Guid()).Take(numAmount);
Run Code Online (Sandbox Code Playgroud)
(请注意我已经使用过,new Guid()
所以你可以删除你的RandomNumber
申报行.如前所述,GUID是一个独特的值,并不适合用作随机数.你也可以使用x => RandomNumber.Next()
,但如果你真的需要一个强大的可靠的舒适,阅读有关Fisher-Yates的信息)
您也可以用简单的数字替换numberHolder数组 Enumerable.Range
所以你的整个代码就会变成(请注意我已经改变了你的方法名称以使用C#约定,方法名称应该在PascalCase中)
public string DrawNumbers(int numLimit, int numAmount)
{
drawHolder = Enumerable.Range(0, numLimit).OrderBy(x => new Guid()).Take(numAmount);
return string.Join(", ", drawHolder);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5511 次 |
最近记录: |