使用VB.NET 2010,如何旋转数组中的元素?

时间:2015-08-22 09:22:40

标签: vb.net vb.net-2010

例如我的数组是{4,6,9,3,1}

我想要循环X次,例如3次,

我希望我的数组成为{3,1,4,6,9}

在VB.NET中有一种简单的方法吗?

谢谢

Function CycleArray(ByVal Arr() As Integer)
    Dim Tmp As Integer = Arr(0)
    Dim Arr2 = Arr.Skip(1).ToArray()
    Arr2(UBound(Arr2) + 1) = Tmp
    Return Arr2
End Function

3 个答案:

答案 0 :(得分:0)

您会发现在大多数情况下使用List比使用Arrays要容易得多。要尝试此操作,请调用以下函数:

    Dim MyArray() As Integer = {4, 6, 9, 3, 1}
    MyArray = LeftRotateArray(MyArray, 3)

该函数如下所示:

Private Function LeftRotateArray(theArray() As Integer, Shift As Integer) As Integer()
    Dim shiftVal As Integer = Shift Mod theArray.Length 'in case Shift is larger than array
    Dim rv As List(Of Integer) = theArray.ToList
    For ct As Integer = 1 To shiftVal
        rv.Add(rv(0))
        rv.RemoveAt(0)
    Next
    Return rv.ToArray
End Function

方法很简单。将数组复制到列表中,然后将元素从前向后移动,直到完成所需的迭代。返回从列表中创建一个数组。

或使用Jon Bentley的'Programming Pearls'中的这种方法:

Private Function LeftRotateArray(theArray() As Integer, Shift As Integer) As Integer()
    Dim shiftVal As Integer = Shift Mod theArray.Length 'in case Shift is larger than array
    Dim rv(theArray.GetUpperBound(0)) As Integer
    Array.Copy(theArray, rv, theArray.Length)
    Array.Reverse(rv, 0, shiftVal)
    Array.Reverse(rv, shiftVal, rv.Length - shiftVal)
    Array.Reverse(rv, 0, rv.Length)
    Return rv
End Function

答案 1 :(得分:0)

由于它基本上是在特定位置切割和粘贴原始数组的一部分,因此可以在一个动作中完成。正如dbasnett所说,如果你专注于清晰的代码,使用ListIEnumerable会更容易。性能明智的其他解决方案可能更好。

    Dim numbers = New Integer() {4, 6, 9, 3, 1}
    Dim result = RotateRight(numbers, 3)

Public Function RotateRight(numbers As Integer(), offset As Integer) As Integer()
    Dim list = numbers.ToList()

    Return list.Skip(offset).Concat(list.Take(offset)).ToArray()
End Function

答案 2 :(得分:0)

我认为你可以做Array.Copy。你需要分两部分来做......

Function CycleArray(Arr() As Integer, cycleTimes As Integer) As Integer()
    Dim Arr2() As Integer
    ReDim Arr2(Arr.Length - 1)
    cycleTimes = cycleTimes Mod Arr.Length
    Array.Copy(Arr, cycleTimes, Arr2, 0, Arr.Length - cycleTimes)
    Array.Copy(Arr, 0, Arr2, Arr.Length - cycleTimes, cycleTimes)
    Return Arr2
End Function