我目前正在尝试创建一个程序,该程序生成1到45之间的随机数,没有重复项。当我使用else语句运行它而没有else语句时我的程序工作它输入数字0,当我使用else语句函数中断时。我想显示1到45之间的随机数,但是变量大小必须决定数组的大小。例如,1到45之间的随机整数,数组大小为35。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomArray
{
public class RandomArrayNoDuplicates
{
static void Main(string[] args)
{
int size = 45;
int[] noDuplicateArray = new int[size];
noDuplicateArray = InitializeArrayWithNoDuplicates(size);
DisplayArray(noDuplicateArray);
ExitProgram();
} //end Main
static Random rng = new Random();
/// <summary>
/// Creates an array with each element a unique integer
/// between 1 and 45 inclusively.
/// </summary>
/// <param name="size"> length of the returned array < 45
/// </param>
/// <returns>an array of length "size" and each element is
/// a unique integer between 1 and 45 inclusive </returns>
///
static void ExitProgram()
{
Console.Write("\n\nPress any key to exit program: ");
Console.ReadKey();
}//end ExitProgram
public static int[] InitializeArrayWithNoDuplicates(int size)
{
int number;
int[] noDuplicates = new int[size];
for (int i = 0; i < size; i++)
{
number = rng.Next(1, size);
if (!noDuplicates.Contains(number))
noDuplicates[i] = number;
// else
// i--;
}
return noDuplicates;
}
static void DisplayArray(int[] noDuplicates)
{
foreach (int element in noDuplicates)
{
Console.Write("\t" + element + "\n");
}
}
}
}
问题在于这段代码:
public static int[] InitializeArrayWithNoDuplicates(int size)
{
int number;
int[] noDuplicates = new int[size];
for (int i = 0; i < size; i++)
{
number = rng.Next(1, size);
if (!noDuplicates.Contains(number))
noDuplicates[i] = number;
// else
// i--;
}
return noDuplicates;
但我不确定如何修复它。我更喜欢使用random.next函数而不是使用enumberable方法。感谢
答案 0 :(得分:1)
请尝试以下操作:
public static int[] InitializeArrayWithNoDuplicates(int size)
{
Random rand = new Random();
return Enumerable.Repeat<int>(0, size).Select((x, i) => new { i = i, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.i).ToArray();
}
代码创建一个等于size的整数数组(Enumerable.Repeat(0,size)),填充零值只是为了得到一个等于size的数组。因此,select会创建一个二维数组,其中i是数字0到大小,rand是随机数。我不再重复。然后代码通过随机数简单地排序二维数组,然后仅提取i值。
答案 1 :(得分:0)
如果你转到Next方法的定义,你会看到
// Exceptions:
// T:System.ArgumentOutOfRangeException:
// minValue is greater than maxValue.
和
rng.Next(1, 0);
引发ArgumentOutOfRangeException异常