0

我有这段代码来随机化字符串数组的内容:

Public Function Randomize_Array(ByVal array() As String) As Array
    Return array.OrderBy(Function() Array_randomizer.Next).ToArray
End Function

问题是我需要进行重载以随机化整数(或任何其他类型的数组),重要提示:我需要保留数组的类型(我的意思是在随机化时不要将整数数组转换为字符串数组)

这是我尝试过的:

Dim IntArray As Array = {1, 2, 3}
Randomize_Array(IntArray)

Dim Array_randomizer As New Random

' The Overload does not works
Public Function Randomize_Array(ByVal array As Array) As Array
    Return array.OrderBy(Function() Array_randomizer.Next).ToArray
End Function
4

1 回答 1

1

你可以这样做:

Public Function Randomize_Array(ByVal array As Array) As Array
    Return array.Cast(Of Object).OrderBy(Function() Array_randomizer.Next).ToArray
End Function

或者对于通用解决方案:

Public Function Randomize_Array(Of T)(ByVal array As T()) As T()
    Return array.OrderBy(Function() Array_randomizer.Next).ToArray
End Function

您可能还对“ Fisher-Yates 算法”感兴趣,该算法在不创建新数组的情况下就地打乱数组元素(因此效率更高)。它看起来像这样:

Public Sub Shuffle(ByVal array As Array)
    Dim randomizer As New Random
    For i As Integer = array.Length To 1 Step -1
        Dim j As Integer = randomizer.Next(i)
        Dim tmp As Object = array(j)
        array(j) = array(i - 1)
        array(i - 1) = tmp
    Next
End Sub
于 2013-06-09T05:29:12.897 回答