Scala program to find the intersection of two arrays

1. Introduction

Finding the intersection of two arrays means identifying the common elements shared by both arrays. This is a fundamental operation in set theory and has various applications in computer science, including in database operations, data analysis, and more. Scala, with its rich collection library, offers efficient ways to compute the intersection of two arrays. Let's explore this in detail.

2. Program Steps

1. Initialize a Scala environment.

2. Declare two sample arrays.

3. Use the intersect method provided by Scala's collection library to find the common elements.

4. Print the intersected array.

5. Execute the program.

3. Code Program

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

    // Find the intersection of the two arrays
    val intersectedArray = findIntersection(array1, array2)

    println(s"Intersection of the two arrays: ${intersectedArray.mkString("[", ", ", "]")}")
  }

  def findIntersection(arr1: Array[Int], arr2: Array[Int]): Array[Int] = {
    arr1.intersect(arr2)
  }
}

Output:

Intersection of the two arrays: [4, 5]

Explanation:

1. We have the IntersectionApp object which acts as a container for our program.

2. Inside the main function, two sample arrays, array1 and array2, are declared.

3. The findIntersection function is designed to determine the common elements of the two input arrays. It uses the intersect method available to Scala arrays. This method returns a new array containing the shared elements.

4. The resulting intersected array is then printed to the console.

5. This example illustrates how straightforward and concise it is to compute the intersection of two arrays in Scala, thanks to its robust standard library.


Comments