问题随机化Array类型的内容

时间:2013-06-09 05:06:04

标签: .net arrays vb.net

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

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

1 个答案:

答案 0 :(得分: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 algorithm'感兴趣它可以在不创建新数组的情况下就地对阵列元素进行混洗(因此效率更高)。它看起来像这样:

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