-1

I'm trying to rotate a List to the right by a certain specified numbers of places. I think that an array (or List) rotation can be seen as a circular, which means elements that fall off the end would wrap around to the beginning, and vice versa. A good example of this could possibly be if we have an array or list, then we rotated it to the right by three places, the result will be as follow:

Initial Array (or List): 20, 30, 40, 50, 60, 70

Rotated to the right by 3 places: 50, 60, 70, 20, 30, 40.

I've written some code down, based of what the little I understand of this concept. I would like to know, what's the correct way to do this manually (without any sort of fancy code nor LINQ) as it will help me to understand it better.

i'm asking for the manual way to solve this problem, not with anything fancy.

public void Test8(List<int> items, int places)
{
    int[] copy = new int[items.Count];
    items.CopyTo(copy, 0);

    for (int i = 0; i < items.Count; i++)
    {
        int RotateRight = (i + places) % items.Count;
        items[i] = copy[RotateRight];

    }

}
Dyrus
  • 3
  • 4

1 Answers1

2

Here is a approache with Linq with Skip() and Take().

List<int> iList = new List<int>() { 20, 30, 40, 50, 60, 70 };
int rotate = 3;
List<int> lResult = iList.Skip(rotate).Concat(iList.Take(rotate)).ToList();

another approach with a simple loop

int[] items = new int[] { 20, 30, 40, 50, 60, 70 };
int[] result = new int[items.Length];
int rotate = 3;

for (int i = 0; i < items.Length; i++)
{
    result[i] = items[(i+rotate)% items.Length];
}
fubo
  • 44,811
  • 17
  • 103
  • 137
  • How could this work with items.Count in the loop instead of items.Length? – Dyrus Jul 19 '16 at 08:07
  • @Dyrus use `.Count()` instead of `.Length` it's the same result - but `.Count()` is a part of `System.Linq.Enumerable` and you wanted a solution without `Linq` – fubo Jul 19 '16 at 08:08