Results from the below:
20,30,40,50,60,70
60,70,20,30,40,50 (Rotate 2)
50,60,70,20,30,40 (Rotate 3)
If you meant to shift each element n indexes to the left, just replace the line list[i] = copy[index];
with list[index] = copy[i];
Then you get these results:
20,30,40,50,60,70
40,50,60,70,20,30 (Rotate 2)
50,60,70,20,30,40 (Rotate 3)
This is a simple working generic method:
static void RotateList<T>(IList<T> list, int places)
{
// circular.. Do Nothing
if (places % list.Count == 0)
return;
T[] copy = new T[list.Count];
list.CopyTo(copy, 0);
for (int i = 0; i < list.Count; i++)
{
// % used to handle circular indexes and places > count case
int index = (i + places) % list.Count;
list[i] = copy[index];
}
}
Usage:
List<int> list = new List<int>() { 20, 30, 40, 50, 60, 70 };
RotateList(list, 3);
Or since I'm a big fan of extension Methods, you can create one:
(By using IList, this method works for arrays also)
public static class MyExtensions
{
public static void RotateList<T>(this IList<T> list, int places)
{
// circular.. Do Nothing
if (places % list.Count == 0)
return;
T[] copy = new T[list.Count];
list.CopyTo(copy, 0);
for (int i = 0; i < list.Count; i++)
{
int index = (i + places) % list.Count;
list[i] = copy[index];
}
}
Usage:
List<int> list = new List<int>() { 20, 30, 40, 50, 60, 70 };
list.RotateList(12); // circular - no changes
int[] arr = new int[] { 20, 30, 40, 50, 60, 70 };
arr.RotateList(3);