我应该在随机数生成器编码中添加什么,所以数字不能连续多次重复?
我的随机数生成器如下所示:
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
答案 0 :(得分:1)
给定N(目前N = 3,但它可能是其他东西,如你所说),尝试构造1,...,N的随机排列,然后按生成的顺序打开文本框。请注意,这意味着您一次生成N个数字并全部使用它们,然后再生成N个。搜索“随机排列”以找到算法。
答案 1 :(得分:1)
将Random实例“rn”移出到Class(Form)级别,这样它只会为Form创建ONCE,并且反复使用同一个实例:
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
答案 2 :(得分:0)
要获得1到N(含)之间的随机整数值,您可以使用以下内容。
CInt(Math.Ceiling(Rnd() * n))
答案 3 :(得分:0)
如果您希望每个号码仅使用一次,则需要执行以下操作:
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