Q:

Array Rotation in Scala

belongs to collection: Scala Array Programs

0

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.

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.  

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to find the odd occurrences in an ar... >>
<< Scala program to create an array of strings...