如果您只有一个所有可能数字的列表(在您的情况下为 0 到 51),然后从列表中删除该数字,这样就不能再次选择它,这将容易得多。尝试这样的事情:
Dim allNumbers As New List (Of Integer)
Dim randomNumbers As New List (Of Integer)
Dim rand as New Random
' Fill the list of all numbers
For i As Integer = 0 To 51 Step 1
allNumbers.Add(i)
Next i
' Grab a random entry from the list of all numbers
For i As Integer = 0 To 51 Step 1
Dim selectedIndex as Integer = rand.Next(0, (allNumbers.Count - 1) )
Dim selectedNumber as Integer = allNumbers(selectedIndex)
randomNumbers.Add(selectedNumber)
allNumbers.Remove(selectedNumber)
' Might as well just add the number to ListBox1 here, too
ListBox1.Items.Add(selectedNumber)
Next i
如果您的目标是将数字放入 ListBox1,那么您甚至不需要“randomNumbers”列表。
编辑:
如果您必须有一个数组,请尝试以下操作:
Function RandomArray(min As Integer, max As Integer) As Integer()
If min >= max Then
Throw New Exception("Min. must be less than Max.)")
End If
Dim count As Integer = (max - min)
Dim randomNumbers(count) As Integer
Dim rand As New Random()
' Since an array of integers sets every number to zero, and zero is possibly within our min/max range (0-51 here),
' we have to initialize every number in the array to something that is outside our min/max range.
If min <= 0 AndAlso max >= 0 Then
For i As Integer = 0 To count
randomNumbers(i) = (min - 1) ' Could also be max + 1
Next i
End If
Dim counter As Integer = 0
' Loop until the array has count # of elements (so counter will be equal to count + 1, since it is incremented AFTER we place a number in the array)
Do Until counter = count + 1
Dim someNumber As Integer = rand.Next(min, max + 1)
' Only add the number if it is not already in the array
If Not randomNumbers.Contains(someNumber) Then
randomNumbers(counter) = someNumber
counter += 1
End If
Loop
Return randomNumbers
End Function
这对你的任务来说已经足够了,但是我的计算机科学家讨厌这个算法。
这就是为什么这种算法不太理想的原因。如果零在您的数字范围内,则您必须循环遍历数组至少 2N 次(如果您从 0 到 51,则需要循环 104 次以上)。这是最好的情况;随着数字范围的扩大,该算法的时间复杂度实际上变得更糟。例如,如果您尝试从 0 到 100,000 运行它,它将很快填充前几千个数字,但随着它的继续,找到一个不在列表中的数字将花费越来越长的时间。当你找到最后几个数字时,在找到最后几个数字之前,你可能已经随机生成了几万亿个不同的数字。如果您假设平均复杂度为 100000!(100,000 阶乘),那么循环将执行几乎十到百万分之一的幂次。
数组更难“洗牌”,因为它是固定大小的,因此您不能像使用列表或集合那样真正添加和删除项目。但是,您可以做的是按顺序用您的数字填充数组,然后进行随机次数的迭代,在其中随机交换两个数字的位置。