Sunday, July 27, 2014

Rotating array

Problem

Write a function to rotate given array clock-wise. i.e. Rotate(int[] a, int k)

Approaches

1. One obvious approach is by using extra memory of 'k', and then rotating the array - it is O(N) and O(k) space.
 
2. Rotating array by '1' and repeating the task for 'k' number of times
 
Below is the approach of achieving the result in O(N) and O(1) space:
 
a. Firstly, reverse the array
b. And then reverse first 'k' elements and reverse remaining elements separately.
 
 
Code Snippet
  1. void swap<T>(ref T x, ref T y)
  2.         {
  3.             T t = x;
  4.             x = y;
  5.             y = t;
  6.         }
  7.         void Reverse(int[] a, int start, int end)
  8.         {
  9.             int i = start, j = end;
  10.             while (i < j)
  11.             {
  12.                 swap<int>(ref a[i], ref a[j]);
  13.                 i++;
  14.                 j--;
  15.             }
  16.         }
  17.         void Rotate(int[] a, int k)
  18.         {
  19.             a.ThrowIfNull("array");
  20.             k.Throw("k", e => e < 0);
  21.             if (a.Length <= 1)
  22.             {
  23.                 return;
  24.             }
  25.             k = k % a.Length;
  26.             this.Reverse(a, 0, a.Length - 1);
  27.             this.Reverse(a, 0, k - 1);
  28.             this.Reverse(a, k, a.Length - 1);
  29.         }

Unit Tests

Code Snippet
  1. [TestMethod]
  2.         public void RotateTests()
  3.         {
  4.             int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  5.             for (int i = 1; i <= a.Length; i++)
  6.             {
  7.                 int k = a.Length - i + 1;
  8.                 int[] b = new int[a.Length];
  9.                 this.Rotate(a, i);
  10.                 for(int j = 0;j<b.Length;j++)
  11.                 {
  12.                     if(k > a.Length)
  13.                     {
  14.                         k = (k % a.Length);
  15.                     }
  16.                     b[j] = k;
  17.                     k++;
  18.                 }
  19.                 for (int j = 0; j < a.Length;j++ )
  20.                 {
  21.                     Assert.IsTrue(a[j] == b[j]);
  22.                 }
  23.                 this.Rotate(a, a.Length - i);
  24.             }
  25.         }

References

No comments:

Post a Comment