Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does code exist, for shifting List elements to left or right by specified amount, in C#?

Tags:

c#

Does code exist, for shifting List elements to left or right by specified amount, in C#?

It is tricky code, it will take some time to write and test special cases, I would rather reuse something if it exists.

Thanks

like image 568
user2381422 Avatar asked Aug 12 '13 06:08

user2381422


People also ask

How do elements shift left in list?

To shift items to the left, we can remove the first element from the list with pop(), and then append it to the end of the list with the append() function. To shift items to the right, we can do the opposite.


1 Answers

Something like this for shift left...

public static void ShiftLeft<T>(List<T> lst, int shifts)
{
    for (int i = shifts; i < lst.Count; i++)
    {
        lst[i - shifts] = lst[i];
    }

    for (int i = lst.Count - shifts; i < lst.Count; i++)
    {
        lst[i] = default(T);
    }
}

For shift right it's a little more tricky, because we must copy in reverse

public static void ShiftRight<T>(List<T> lst, int shifts)
{
    for (int i = lst.Count - shifts - 1; i >= 0; i--)
    {
        lst[i + shifts] = lst[i];
    }

    for (int i = 0; i < shifts; i++)
    {
        lst[i] = default(T);
    }
}

With arrays it's a lot more simple, because Array has very powerful methods:

public static void ShiftLeft<T>(T[] arr, int shifts)
{
    Array.Copy(arr, shifts, arr, 0, arr.Length - shifts);
    Array.Clear(arr, arr.Length - shifts, shifts);
}

public static void ShiftRight<T>(T[] arr, int shifts)
{
    Array.Copy(arr, 0, arr, shifts, arr.Length - shifts);
    Array.Clear(arr, 0, shifts);
}

And yes, Array.Copy is protected against overleap: If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.

like image 195
xanatos Avatar answered Sep 24 '22 21:09

xanatos