w3resource

Scala Programming: Rotate one element left of an given array (length 1 or more) of integers

Scala Programming Array Exercise-8 with Solution

Write a Scala program to rotate one element left of an given array (length 1 or more) of integers.

Sample Solution:

Scala Code:

object Scala_Array
{
 
 def rotate_left(arr: Array[Int]): Array[Int] = {
    if (arr.length < 1) false 
    arr.tail :+ arr.head
   }
  def main(args: Array[String]): Unit = 
   {
   val nums1 = Array(1,2,3,4,5,6,7)
   println("Original Array elements:")
   // Print all the array elements
      for ( x <- nums1 ) {
         print(s"${x}, ")        
       }
   println("\nRotate left one element:")  
   var result_left1 = rotate_left(nums1)
        for ( x <- result_left1 ) {
         print(s"${x}, ")        
         }   
   val nums2 = Array(1,2)
   println("\nOriginal Array elements:")
   // Print all the array elements
      for ( x <- nums2 ) {
         print(s"${x}, ")        
       }
   println("\nRotate left one element:")  
   var result_left2 = rotate_left(nums2)
        for ( x <- result_left2 ) {
         print(s"${x}, ")        
         }   
   val nums3 = Array(100)
   println("\nOriginal Array elements:")
   // Print all the array elements
      for ( x <- nums3 ) {
         print(s"${x}, ")        
       }
   println("\nRotate left one element:")  
   var result_left3 = rotate_left(nums3)
        for ( x <- result_left3 ) {
         print(s"${x}, ")        
         }   
   }
}

Sample Output:

Original Array elements:
1, 2, 3, 4, 5, 6, 7, 
Rotate left one element:
2, 3, 4, 5, 6, 7, 1, 
Original Array elements:
1, 2, 
Rotate left one element:
2, 1, 
Original Array elements:
100, 
Rotate left one element:
100, 

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to remove a specific element from an given array.
Next: Write a Scala program to find the maximum and minimum value of an array of integers.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.