w3resource

Scala Program: Find the largest element with pattern matching

Scala Control Flow Exercise-10 with Solution

Write a Scala program to find the largest element in an array using pattern matching.

Sample Solution:

Scala Code:

object LargestElementFinder {
  def main(args: Array[String]): Unit = {
    // Array containing the numbers
    val numbers: Array[Int] = Array(23, 36, 36, 55, 19, 8) 
    // Print all the array elements
    println("Original Array elements:")
    for ( x <- numbers ) {
       print(s"${x}, ")        
     }

    val largestElement: Option[Int] = findLargestElement(numbers)

    largestElement match {
      case Some(largest) => println(s"\nThe largest element is: $largest")
      case None          => println("\nThe array is empty.")
    }
  }

  def findLargestElement(numbers: Array[Int]): Option[Int] = {
    numbers match {
      case Array()    => None
      case Array(x)   => Some(x)
      case Array(x, y, rest @ _*) =>
        val maxRest = findLargestElement(Array(y) ++ rest.toArray)
        if (x > maxRest.get) Some(x) else maxRest
    }
  }
}

Sample Output:

Original Array elements:
23, 36, 36, 55, 19, 8, 
The largest element is: 55

Explanation:

In the above exercise,

The function 'findLargestElement()' takes an array as input and returns an Option[Int] representing the largest element. The function uses pattern matching to handle different cases:

  • If the numbers array is empty, it returns None.
  • If the numbers array contains only one element, it returns that element wrapped in Some.
  • If the numbers array contains more than one element, it uses a variable pattern rest @ _* to capture the remaining elements after the first two (x and y). It recursively calls findLargestElement with an array composed of y and the remaining elements (rest), converts it to an array, and compares the result (maxRest) with x. If x is greater than maxRest, it returns Some(x); otherwise, it returns maxRest.
  • In the "main()" method, we call the "findLargestElement()" function passing the numbers array and assigning the result to largestElement, which will be an Option[Int]. We use pattern matching to handle the Some and None cases and print the largest element or a message indicating an empty array.

At the end of the program, the largest element in the array will be displayed.

Scala Code Editor :

Previous: Count vowels with if/else and pattern matching.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.