通過給定班次旋轉陣列的通用方法示例

我想指出,當換檔值為負時我們向左旋轉,當值為正時我們向右旋轉。

    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)