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

时间:2015-05-14 12:06:29

标签: .net vb.net random

这是我的代码,我得到的组合多次包含相同的数字,因此它们检查不起作用。我需要它以任何顺序获得组合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

2 个答案:

答案 0 :(得分:2)

我认为你打算做的是将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

答案 1 :(得分:1)

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

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填充数组,OrderBy对其进行排序,使用简单的lambda expression来获取订单随机。