Scala program to find the common elements in two arrays

1. Introduction

Finding common elements between two arrays is a common operation in data analysis and processing. In this post, we will create a Scala program that identifies the shared elements between two arrays.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define two arrays.

4. Implement a function to determine the common elements.

5. Invoke the function and display the shared elements.

6. Execute the program.

3. Code Program

object CommonElementsApp {
  def main(args: Array[String]): Unit = {
    // Define two arrays
    val array1 = Array(1, 2, 3, 4, 5)
    val array2 = Array(4, 5, 6, 7, 8)

    println(s"Array 1: ${array1.mkString(", ")}")
    println(s"Array 2: ${array2.mkString(", ")}")

    // Find and print common elements
    val commonElements = findCommonElements(array1, array2)
    println(s"\nCommon Elements: ${commonElements.mkString(", ")}")
  }

  // Function to find common elements
  def findCommonElements(arr1: Array[Int], arr2: Array[Int]): Array[Int] = {
    arr1.intersect(arr2)
  }
}

Output:

Array 1: 1, 2, 3, 4, 5
Array 2: 4, 5, 6, 7, 8
Common Elements: 4, 5

Explanation:

1. We initiate the program with an object named CommonElementsApp. Within this object, the main method is the entry point.

2. We define array1 and array2 containing several integers.

3. A message is printed to display the contents of both arrays.

4. The findCommonElements function is devised to capture the common elements. It employs Scala's built-in intersect method which returns the shared elements of two arrays.

5. Within the main function, we call the findCommonElements method, retrieve the shared elements, and then exhibit them.

6. The output showcases the common elements between the two pre-defined arrays.


Comments