How to shift the start of an array in C#?

后端 未结 8 2020
渐次进展
渐次进展 2020-12-18 07:31

I\'m trying to reorganize an array based on the first occurrence of a value (thus simulating similar functionality to a circular array.)

For example, in the followin

8条回答
  •  忘掉有多难
    2020-12-18 07:57

    To begin with, do a linear search to find the first occurrence of the value that you want to make the first element:

    // value contains the value to find.
    
    int skip;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] == value)
        {
            skip = i;
            break;
        }
    }
    
    // skip contains the index of the element to put at the front.
    // Equivalently, it is the number of items to skip.
    // (I chose this name for it because it makes the subtractions
    // in the Array.Copy implementation more intuitive.)
    

    Do you want to change the actual array? Then do what Thorsten Dittmar suggests:

    int[] array = new int[] { 2, 3, 6, 1, 7, 6 };
    int[] result = new int[array.Length];
    
    int skip = 2; // So that array[skip] will be result[0] at the end
    
    Array.Copy(array, skip, result, 0, array.Length - skip);
    Array.Copy(array, 0, result, array.Length - skip, skip);
    

    Do you want to just view the array in the new order, without doing anything else? Then index it like so:

    array[(i + skip) % array.Length]  // Instead of array[i]
    

    Edit: Just for laughs, an implementation of Jon Skeet's suggestion to implement the copy while using only a single buffer value (sourceValue):

    // GCD gives the greatest common divisor
    int gcd = GCD(array.Length, skip);
    
    // period is the length of the permutation cycles in our rotation.
    int period = array.Length / gcd;
    
    int max = array.Length / period;
    for (int i = 0; i < max; i++)
    {
        int sourceIndex = i;
        int sourceValue = array[sourceIndex];
    
        for (int n = 1; n <= period; n++)
        {
            int destinationIndex = (sourceIndex + array.Length - skip) % array.Length;
    
            int temp = array[destinationIndex];
            array[destinationIndex] = sourceValue;
            sourceValue = temp;
    
            sourceIndex = destinationIndex;
        }
    }
    

提交回复
热议问题