adiajdiadj
adiajdiadj

Reputation: 41

C# Shift entire array by 1

I wanted to shift the entire array by one. Example: if the array goes from [0] to [19] i want it to be from [1] to [20], [0] dissapears.

Current approach (it's wrong):

   shiftRight(operationsList.ToArray()));


    public Operation3D[] shiftRight(Operation3D[] arr)
    {
        Operation3D[] demo = new Operation3D[arr.Length];

        for (int i = 1; i < arr.Length; i++)
        {
            demo[i] = arr[i - 1];
        }

        demo[0] = arr[demo.Length - 1];

        return demo;
    }

Upvotes: 1

Views: 2251

Answers (1)

Matt Rowland
Matt Rowland

Reputation: 4595

Moving the elements to the right will require a new array because of the resizing. There is no way to make index 0 disappear. It will have to exist but it can be null.

The code below will accomplish this:

public Operation3D[] shiftRight(Operation3D[] arr)
{
    Operation3D[] result = new Operation3D[arr.Length + 1];
    Array.Copy(arr, 0, result, 1, arr.Length);
    return result;
}

Upvotes: 5

Related Questions