我应该在随机数生成器编码中添加什么,这样数字就不会连续重复更多次?
我的随机数生成器看起来像这样:
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
给定 N(目前 N = 3,但正如你所说,它可能是别的东西),尝试构造 1、...、N 的随机排列,然后按生成的顺序打开文本框。请注意,这意味着您一次生成 N 个数字并将它们全部用完,然后生成更多 N 个数字。搜索"随机排列"以找到算法。
将您的随机实例"rn"移出到类(表单)级别,以便它只为表单创建一次,并且同一实例被一遍又一遍地使用:
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
要获取介于 1 和 N(含)之间的随机整数值,您可以使用以下内容。
CInt(Math.Ceiling(Rnd() * n))
如果你希望每个数字只使用一次,你需要做这样的事情:
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