Tuesday, October 31, 2017

Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. How many different ways do you know to solve this problem?

Using LINQ
            var arr = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            //Rorate array to the right
            var k = 10 % 7;

            //should move to the beginnning
            var output = arr.Skip(arr.Count - k).ToList();
            output.AddRange(arr.Take(arr.Count - k));
         

            Console.ReadLine();

Using Add Method

 var arr = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            //Rorate array to the right
            var k = 10 % 7;
            //Move the head of the array to the tail number of times = k
            for (int i = 0; i < arr.Count - k; i++)
            {
                arr.Add(arr[0]);
                arr.RemoveAt(0);
            }

Using Insert
 var arr = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            //Rorate array to the right
            var k = 10 % 7;
            //Move the head of the array to the tail number of times = k
            for (int i = 0; i < k; i++)
            {
                arr.Insert(0, arr.Last());
                arr.RemoveAt(arr.Count -1);
            }

No comments: