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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With