洗牌字符串数组时的问题

Problems when shuffling an array of strings

我正在尝试打乱一组字符串,下面是我已有的代码段。但是,此代码的一个问题是,很多时候它会打乱内容但会排除一个值。例如洗牌 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

作为一个简单而干净的选项,您可以这样打乱字符串列表:

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))