改组字符串数组时出现问题

时间:2015-10-28 19:01:48

标签: vb.net random shuffle

我试图改组一个字符串数组,下面是我已经拥有的代码段。但是,此代码的一个问题是,它很多时候会对内容进行混洗,但会排除一个值。例如,改组A,B,C,D它将执行此操作:A,D,C。

非常感谢任何帮助。

Private rnd = New Random()

Public Sub Shuffle(ByRef List() As String)
    Dim Limit As Integer = List.Length - 1

    For i = Limit To 0 Step -1
        Dim j As Integer = rnd.Next(0, i + 1)
        Dim temp As String = List(i)
        List(i) = List(j)
        List(j) = temp
    Next
End Sub

1 个答案:

答案 0 :(得分:1)

作为一个简单而干净的选项,您可以通过这种方式随机填充字符串列表:

Public Function Shuffle(source As List(Of String)) As List(Of String)
    Dim rnd = New Random(System.DateTime.Now.Millisecond)
    Return source.OrderBy(Function(item) rnd.Next()).ToList()
End Function

以下是用法:

Dim list = New List(Of String) From {"A", "B", "C", "D"}
Dim result = Shuffle(list)
MessageBox.Show(String.Join("," , result))