Dan Hayes
Dan Hayes

Reputation: 97

Random number generator check not working

Here is my code, I'm getting combinations that contain the same number more than once so they check isn't working. I need it to get the combination 1,2,3,4 in any order. thanks for any help.

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

Upvotes: 1

Views: 88

Answers (2)

Zohar Peled
Zohar Peled

Reputation: 82474

If you know in advance the numbers you need, you better add them to the array sequentially and just sort the array to a random order when you need to.
Try this:

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)

This code uses Linq Enumerable to fill the array, OrderBy to sort it, and a simple lambda expression to get the order random.

Upvotes: 1

Matt Wilko
Matt Wilko

Reputation: 27322

I think what you intended to do was to put 4 consecutive numbers into a random order. Instead you are generating a random number four times (which could easily duplicate given the small range of numbers).

A solution would be as follows:

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

Upvotes: 2

Related Questions