对已发布代码的简单跟踪揭示了一些问题。具体来说,就行了……
if (x[i] == x[j]) break;
如果随机数“已经”在数组中,那么只需跳出j 循环即可将当前i 值跳过到x 数组中。这意味着每当找到重复项时,x[i] 将是默认值 0(零),然后被跳过。
外部i循环显然是循环通过xint数组,这很清楚,看起来还可以。然而,第二个内部循环不可能真的是一个for 循环......这就是为什么......基本上你需要找到一个随机的int,然后遍历现有的ints,看看它是否已经存在。鉴于此,理论上您可以“多次”获取相同的随机数,然后才能获得唯一的随机数。因此,在这种情况下……你真的不知道要循环多少次才能找到这个唯一的数字。
话虽如此,它可能有助于“打破”你的问题。我猜测与x 数组中现有的ints 相比,返回“唯一”int 的“方法”可能会派上用场。创建一个无限的while 循环,在这个循环中,我们将获取一个随机数,然后循环通过“现有的”ints。如果随机数不是重复的,那么我们可以简单地返回这个值。这就是这个方法所做的一切,它可能如下所示。
private static int GetNextInt(Random r, int[] x, int numberOfRandsFound) {
int currentRand;
bool itemAlreadyExist = false;
while (true) {
currentRand = r.Next(RandomNumberSize);
itemAlreadyExist = false;
for (int i = 0; i < numberOfRandsFound; i++) {
if (x[i] == currentRand) {
itemAlreadyExist = true;
break;
}
}
if (!itemAlreadyExist) {
return currentRand;
}
}
}
注意:现在是描述这段代码中可能出现的无限循环的好时机……
目前,随机数和数组的大小是相同的,但是,如果数组大小“大于”随机数扩展,那么上面的代码将永远不会退出。例如,如果当前 x 数组的大小设置为 11 并且随机数保留为 10,那么您将永远无法设置 x[10] 项,因为所有可能的随机数都已使用。我希望这是有道理的。
一旦我们有了上面的方法……剩下的应该是相当简单的。
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
int numberOfRandsFound = 0;
int[] ArrayOfInts = new int[DataSize];
int currentRand;
for (int i = 0; i < ArrayOfInts.Length; i++) {
currentRand = GetNextInt(random, ArrayOfInts, numberOfRandsFound);
ArrayOfInts[i] = currentRand;
numberOfRandsFound++;
}
for (int i = 0; i < ArrayOfInts.Length; i++) {
Console.WriteLine(ArrayOfInts[i]);
}
Console.ReadKey();
}
最后正如其他人所提到的,使用List<int> 会更容易...
static int DataSize;
static int RandomNumberSize;
static void Main(string[] args) {
Random random = new Random();
DataSize = 10;
RandomNumberSize = 10;
List<int> listOfInts = new List<int>();
bool stillWorking = true;
int currentRand;
while (stillWorking) {
currentRand = random.Next(RandomNumberSize);
if (!listOfInts.Contains(currentRand)) {
listOfInts.Add(currentRand);
if (listOfInts.Count == DataSize)
stillWorking = false;
}
}
for (int i = 0; i < listOfInts.Count; i++) {
Console.WriteLine(i + " - " + listOfInts[i]);
}
Console.ReadKey();
}
希望这会有所帮助;-)