Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we rotate an array to the left?

EX: I have an array {1, 2, 3, 4, 5} and an integer number 7 It will rotate 7 spaces to the right like: {4, 5, 1, 2, 3}

I also have that array {1, 2, 3, 4, 5} and an integer number -7 It will rotate 7 spaces to the left like: {3, 4, 5, 1, 2}

I have rotated the array to the right by using:

for(int i = 0; i < data.length; i++){
              result[(i+n) % data.length ] = data[i];
            }

But how can we rotate an array to the left?

like image 666
Khuong Avatar asked Jun 30 '15 02:06

Khuong


People also ask

What does it mean to left rotate the array?

Left rotation refers to the following. In an array, moving all items to the next lower location. The first item is moved to the last location, which is now vacant. In a list, removing the head and inserting it at the tail.

How do you rotate an array to the right?

The array can be right rotated by shifting its elements to a position next to them which can be accomplished by looping through the array in reverse order (loop will start from the length of the array -1 to 0) and perform the operation arr[j] = arr[j-1].


1 Answers

Rotating to the left by n is the same as rotating to the right by length-n.

Rotate right (for positive n):

for(int i = 0; i < data.length; i++){
    result[(i+n) % data.length ] = data[i];
}

Rotate left (for positive n):

for(int i = 0; i < data.length; i++){
    result[(i+(data.length-n)) % data.length ] = data[i];
}

This way you can avoid a modulo of a negative number.

If you want to input an integer n that rotates right if n is positive and left if n is negative, you can do it like this:

 int[] rotateArray(int n, int[] data)
 {
      if(n < 0) // rotating left?
      {
          n = -n % data.length; // convert to +ve number specifying how 
                                // many positions left to rotate & mod
          n = data.length - n;  // rotate left by n = rotate right by length - n
      }
      int[] result = new int[data.length];
      for(int i = 0; i < data.length; i++){
          result[(i+n) % data.length ] = data[i];
      }
      return result;
 }
like image 194
samgak Avatar answered Oct 17 '22 20:10

samgak