# Array Rotation in Scala

Here, will learn about cyclic array rotation in Scala, and implementing a Scala program to rotate array elements.
Submitted by Shivang Yadav, on April 05, 2020

### Array Rotation

Array rotation is the process of shifting elements of the array in a specific direction and rotate the last element to first or first to last based on the direction of rotation of the array.

If you need some basic information on arrays in Scala please read here: Arrays in Scala.

There are two types of array rotation:

1. Lift Shift: Leftward shifting of elements from index n to n-1, and shift element at the first index to the last index.
2. Right Shift: Rightward shifting of elements from index n-1 to n, and shift element at last index to the first index.

Example:

```    Array: {2, 5, 7, 9, 1, 3}
Left shifted array: {5, 7, 9, 1, 3, 2}
Right shifted array: {3, 2, 5, 7, 9, 1}
```

Now, to left rotate array by n elements, we will first store the last element of the array in a temporary variable. And run a loop from last to first. And copy element at the n-1 position to n and so on.

Program:

```object MyClass {
def rotateArray(A: Array[Int], K: Int): Array[Int] = {
if (A.isEmpty) A
else rotate(A.toList, K).toArray
}

def rotateStepwise(l: List[Int]) = {
l.take(l.size - 1).+:(l.last)
}

def rotate(l: List[Int], K: Int): List[Int] = {
if (K == 0) l
else rotate(rotateStepwise(l), K - 1)
}

def main(args: Array[String]) {
var arr = Array(1, 5, 6, 8, 12, 7)
print("Initial Array : ")
for(i <- 0 to arr.length-1){
print(arr(i)+" ")
}
println()
var a = rotateArray(arr, 1)
print("Array after right rotation : ")
for(i <- 0 to a.length-1){
print(a(i)+" ")
}
}
}
```

Output

```Initial Array : 1 5 6 8 12 7
Array after right rotation : 7 1 5 6 8 12
```

Explanation:

In this above code, we have a function that is used to right rotate an array by k steps. The function calls another function which does the rotation work. The function calls a function to rotate the array single step k times.

Preparation

What's New

Top Interview Coding Problems/Challenges!