虽然带有整数的列表不包含整数生成随机数
While list with integer is not contains integer generate random number
我该如何进行这项工作,因为当列表中存在随机数 x 时要生成,直到列表中不存在数字 x 为止。所以生成直到它找到列表中不存在的数字。
Dim listwithdeck As New List(Of Integer)
While listwithdeck.Contains(num) = False
MessageBox.Show(num)
num = rnd.Next(2, 15)
listwithdeck.Add(num)
End While
此代码将 运行 直到生成重复的随机数。
Private rnd As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim num As Integer
Dim listwithdeck As New List(Of Integer)
Do
num = rnd.Next(2, 15)
If listwithdeck.Contains(num) Then
Exit Do
Else
listwithdeck.Add(num)
End If
Loop
For Each i In listwithdeck
Debug.Print(i.ToString)
Next
End Sub
如果您正在寻找两个数字之间的随机列表,试试这个。
对于 2 和 15 调用将是 RandList(2,16).
Private Shared PRNG As New Random
''' <summary>
''' returns a list of random integers between minIncl and maxExcl -1
''' </summary>
''' <param name="minIncl">minimum number</param>
''' <param name="maxExcl">maximum number, not included</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function RandList(minIncl As Integer, maxExcl As Integer) As List(Of Integer)
Dim rv As IEnumerable(Of Integer)
rv = Enumerable.Range(minIncl, maxExcl - minIncl).OrderBy(Function() PRNG.Next)
Return rv.ToList
End Function
我该如何进行这项工作,因为当列表中存在随机数 x 时要生成,直到列表中不存在数字 x 为止。所以生成直到它找到列表中不存在的数字。
Dim listwithdeck As New List(Of Integer)
While listwithdeck.Contains(num) = False
MessageBox.Show(num)
num = rnd.Next(2, 15)
listwithdeck.Add(num)
End While
此代码将 运行 直到生成重复的随机数。
Private rnd As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim num As Integer
Dim listwithdeck As New List(Of Integer)
Do
num = rnd.Next(2, 15)
If listwithdeck.Contains(num) Then
Exit Do
Else
listwithdeck.Add(num)
End If
Loop
For Each i In listwithdeck
Debug.Print(i.ToString)
Next
End Sub
如果您正在寻找两个数字之间的随机列表,试试这个。
对于 2 和 15 调用将是 RandList(2,16).
Private Shared PRNG As New Random
''' <summary>
''' returns a list of random integers between minIncl and maxExcl -1
''' </summary>
''' <param name="minIncl">minimum number</param>
''' <param name="maxExcl">maximum number, not included</param>
''' <returns></returns>
''' <remarks></remarks>
Private Function RandList(minIncl As Integer, maxExcl As Integer) As List(Of Integer)
Dim rv As IEnumerable(Of Integer)
rv = Enumerable.Range(minIncl, maxExcl - minIncl).OrderBy(Function() PRNG.Next)
Return rv.ToList
End Function