通过给定班次旋转数组的通用方法示例

我想指出,当换档值为负时我们向左旋转,当值为正时我们向右旋转。

    public static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        int shiftCount = 1;
        Rotate(ref array, shiftCount);
        Console.WriteLine(string.Join(", ", array));
        // Output: [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]

        array = new []{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        shiftCount = 15;
        Rotate(ref array, shiftCount);
        Console.WriteLine(string.Join(", ", array));
        // Output: [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]

        array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        shiftCount = -1;
        Rotate(ref array, shiftCount);
        Console.WriteLine(string.Join(", ", array));
        // Output: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

        array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        shiftCount = -35;
        Rotate(ref array, shiftCount);
        Console.WriteLine(string.Join(", ", array));
        // Output: [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
    }

    private static void Rotate<T>(ref T[] array, int shiftCount)
    {
        T[] backupArray= new T[array.Length];

        for (int index = 0; index < array.Length; index++)
        {
            backupArray[(index + array.Length + shiftCount % array.Length) % array.Length] = array[index];
        }

        array = backupArray;
    }

在这段代码中重要的是我们在旋转后找到新索引值的公式。

(index + array.Length + shiftCount%array.Length)%array.Length

以下是有关它的更多信息:

(shiftCount%array.Length) - >我们将移位值规范化为数组的长度(因为在长度为 10 的数组中,移位 1 或 11 是相同的,-1 和 -11 相同)。

array.Length +(shiftCount%array.Length) - >这是由左旋转完成的,以确保我们不会进入负索引,而是将其旋转到数组的末尾。没有它,对于索引 0 长度为 10 且旋转为 -1 的数组,我们将进入负数(-1)而不是得到实际旋转索引值,即 9.(10 +( - 1%10)= 9)

index + array.Length +(shiftCount%array.Length) - >在这里说不多,因为我们将旋转应用于索引以获取新索引。 (0 + 10 +( - 1%10)= 9)

index + array.Length +(shiftCount%array.Length)%array.Length - >第二个规范化确保新索引值不会超出数组,而是旋转数组开头的值。它适用于右旋转,因为在长度为 10 的数组中,没有它用于索引 9 和旋转 1,我们将进入索引 10,它位于数组之外,并且不会得到实际旋转索引值为 0.((9 + 10 +(1%10))%10 = 0)