VB.NET数组随机化

时间:2013-11-17 16:23:53

标签: vb.net

我有一个包含6个元素的数组,我希望每次随机填充18个文本框。我只想重复这个项目2次。我有这段代码:

 FlatTextBox1.Text =   (subjects.Item(Int(Rnd() * (subjects.Count - 1))))
FlatTextBox2.Text =   (subjects.Item(Int(Rnd() * (subjects.Count - 1))))

。 。 。 。 。

一直持续到最后。现在问题是有些项目重复了3次,其他项目重复1次,所以没有平等。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

假设你输了一个拼写错误并希望重复3次,而不是2次,因为3 * 6 = 18:

Public Class Form1

    Private R As New Random
    Private subjects() As String = {"cat", "dog", "fish", "hamster", "lizard", "bird"}

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim values As New List(Of String)
        values.AddRange(subjects)
        values.AddRange(subjects)
        values.AddRange(subjects)

        Dim index As Integer
        Dim matches() As Control
        For i As Integer = 1 To 18
            index = R.Next(values.Count)
            matches = Me.Controls.Find("FlatTextBox" & i, True)
            matches(0).Text = values(index)
            values.RemoveAt(index)
        Next
    End Sub

End Class