随机数生成器检查不起作用

Random number generator check not working

这是我的代码,我多次收到包含相同数字的组合,因此它们无法正常工作。我需要它以任何顺序获得组合 1,2,3,4。感谢您的帮助。

Dim RdmPlace(3) As String
Dim i As Integer = 0
Private Sub Rnd_Btn_Click(sender As Object, e As EventArgs) Handles Rnd_Btn.Click   
    For Count As Integer = 1 To 4
        GetRandom()
        i = i + 1
    Next
    Entry1_Txt.Text = RdmPlace(0)
    Entry2_Txt.Text = RdmPlace(1)
    Entry3_Txt.Text = RdmPlace(2)
    Entry4_Txt.Text = RdmPlace(3)
End Sub
Sub GetRandom()
    Randomize()
    Dim check As Integer = 1
    Dim RndValue As Integer = CInt(Int((4 * Rnd()) + 1))
    For Each value As Integer In RdmPlace
        If value = RndValue Then
            GetRandom()
        End If
    Next
    RdmPlace(i) = RndValue
End Sub

Private Sub Reset_Btn_Click(sender As Object, e As EventArgs) Handles Reset_Btn.Click
    Entry1_Txt.Text = Nothing
    Entry2_Txt.Text = Nothing
    Entry3_Txt.Text = Nothing
    Entry4_Txt.Text = Nothing
    i = 0
    For clear As Integer = 0 To 3
        RdmPlace(clear) = Nothing
    Next
End Sub

如果您事先知道所需的数字,最好按顺序将它们添加到数组中,并在需要时将数组排序为随机顺序。
试试这个:

Dim rnd As New System.Random()
Dim RdmPlace(3) As int
' Whenever you need a new random order:
RdmPlace = Enumerable.Range(1, 4).OrderBy(Function() rnd.Next)

此代码使用 Linq Enumerable to fill the array, OrderBy to sort it, and a simple lambda expression 随机获取顺序。

我认为您的意图是将 4 个连续的数字随机排列。相反,您生成了一个随机数四次(鉴于数字范围较小,很容易复制)。

解决方案如下:

Dim list As New List(Of Integer)({1, 2, 3, 4})
Shuffle(list)

Private Shared _rng As New Random()
Public Shared Sub Shuffle(Of T)(aList As IList(Of T))
    Dim n = aList.Count
    Do While (n > 1)
        n -= 1
        Dim k As Integer = _rng.Next(n + 1)
        Dim value As T = aList(k)
        aList(k) = aList(n)
        aList(n) = value
    Loop
End Sub