0

我应该在随机数生成器编码中添加什么,以便数字不会连续重复多次?

我的随机数生成器如下所示:

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
4

4 回答 4

1

将您的 Random 实例“rn”移到 Class (Form) 级别,这样它只会为 Form 创建一次,并且会一遍又一遍地使用同一个实例:

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
于 2013-10-29T22:18:43.053 回答
1

给定 N(目前 N = 3,但如您所说,它可能是其他值),尝试构建 1、...、N 的随机排列,然后按生成的顺序打开文本框。请注意,这意味着您一次生成 N 个数字并将它们全部用完,然后再生成 N 个。搜索“随机排列”以找到算法。

于 2013-10-29T22:13:53.553 回答
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
于 2013-10-29T22:23:13.023 回答
0

要获得 1 和 N(含)之间的随机整数值,您可以使用以下命令。

CInt(Math.Ceiling(Rnd() * n))
于 2013-10-29T21:47:42.033 回答