w3resource

Scala Programming: Test the equality of two arrays

Scala Programming Array Exercise-21 with Solution

Write a Scala program to test the equality of two arrays.

Sample Solution:

Scala Code:

object scala_basic {  
   
   def test(my_array1: Array[Int], my_array2: Array[Int]) : Boolean = {
     var equalOrNot = true;
     if(my_array1.length == my_array2.length)
      {
      for (i <- 0 to  my_array1.length-1) 
         {
          if(my_array1(i) != my_array2(i))
           {
             equalOrNot = false;             
           }
        }
      }
      else
      {
        equalOrNot  = false;
      }  
      if  (equalOrNot) true
      else false
     }         
     def main(args: Array[String]): Unit = {  
       //Call the following Java class for some array operation
       import java.util.Arrays;
       var arr1 =  Array(2, 5, 7, 9, 11);
       var arr2 =  Array(2, 5, 7, 9, 11);
       println("Original Array1 : "+Arrays.toString(arr1));
       println("Original Array2 : "+Arrays.toString(arr2));     
       println("Whether the said two arrays are equal?")
       println(test(arr1,arr2))       
       var arr3 =  Array(2, 5, 7, 9, 11);
       var arr4 =  Array(2, 5, 7, 9, 10);
       println("Original Array1 : "+Arrays.toString(arr3));
       println("Original Array2 : "+Arrays.toString(arr4)); 
       println("Whether the said two arrays are equal?")
       println(test(arr3,arr4))
    }
}

Sample Output:

Original Array1 : [2, 5, 7, 9, 11]
Original Array2 : [2, 5, 7, 9, 11]
Whether the said two arrays are equal?
true
Original Array1 : [2, 5, 7, 9, 11]
Original Array2 : [2, 5, 7, 9, 10]
Whether the said two arrays are equal?
false

Scala Code Editor :

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

Previous: Write a Scala program to find the second smallest element from a given array of integers.

Next: Write a Scala program to find a missing number in an array of integers.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/array/scala-array-exercise-21.php