user2932903
user2932903

Reputation: 1

Vb.net Random Number generator repeats same numbers

What should i add to random number generator coding, so numbers wont repeat themselves more times in a row?

My random number generator looks like this:

Dim rn As New Random
TextBox1.Text = rn.Next(1, 4)
If TextBox1.Text = 1 Then
    Form4.Show()
    Form4.Timer1.Start()
End If

If TextBox1.Text = 2 Then
    Form7.Show()
    Form7.Timer1.Start()
End If

If TextBox1.Text = 3 Then
   Form8.Show()
   Form8.Timer1.Start()
End If

Upvotes: 0

Views: 4040

Answers (4)

Douglas Barbin
Douglas Barbin

Reputation: 3615

If you want each number only used once, you need to do something like this:

Const FirstNumber As Integer = 1
Const LastNumber As Integer = 5

' Fill the list with numbers
Dim numberList as New List(Of Integer)
For i As Integer = FirstNumber To LastNumber Step 1
    numberList.Add(i)
Next i

Dim rand as New Random()
While numberList.Count > 0
    ' draw a random number from the list
    Dim randomIndex As Integer = rand.Next(0, numberList.Count - 1)
    Dim randomNumber As Integer = numberList(randomIndex)

    ' Do stuff with the number here        
    TextBox1.Text = randomNumber

    ' remove the number from the list so it can't be used again
    numberList.RemoveAt(randomIndex)
End While

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

Move your Random instance, "rn", out to Class (Form) level so it only gets created ONCE for the Form, and the same instance gets used over and over:

Public Class Form1

    Private rn As New Random

    Private Sub SomeMethod()
        TextBox1.Text = rn.Next(1, 4)
        If TextBox1.Text = 1 Then
            Form4.Show()
            Form4.Timer1.Start()
        End If

        If TextBox1.Text = 2 Then
            Form7.Show()
            Form7.Timer1.Start()
        End If

        If TextBox1.Text = 3 Then
            Form8.Show()
            Form8.Timer1.Start()
        End If
    End Sub

End Class

Upvotes: 1

Robert Dodier
Robert Dodier

Reputation: 17576

Given N (at present N = 3 but it could be something else, as you say), try to construct a random permutation of 1, ..., N, then open the text boxes in the order that is generated. Note that that means you're generating N numbers at a time and using them all up, then generating N more. Search for "random permutation" to find an algorithm.

Upvotes: 1

Ken VeArd
Ken VeArd

Reputation: 495

To get a random integer value between 1 and N (inclusive) you can use the following.

CInt(Math.Ceiling(Rnd() * n))

Upvotes: 0

Related Questions