w3resource

Scala Program: Find the largest element with pattern matching


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


Pre-Knowledge (Before you start!)

  • Basic Scala Syntax: Familiarity with writing and running Scala programs.
  • Arrays in Scala: Knowledge of creating and working with arrays, including iterating through elements.
  • Pattern Matching: Understanding how to use pattern matching for decision-making and handling different cases.
  • Option Type: Awareness of the Option type in Scala and its use for handling optional values like Some and None.
  • Recursive Functions: Ability to write recursive functions to solve problems by breaking them into smaller subproblems.
  • Printing Output: Familiarity with the println() function to display output on the screen.

Hints (Try before looking at the solution!)

  • Define the Main Object: Create an object with a main method, which serves as the entry point of the program.
  • Initialize the Array: Declare and initialize an array containing the numbers whose largest element you want to find.
  • Write the Recursive Function: Create a function that uses pattern matching to handle three cases:
    • An empty array, returning None.
    • An array with one element, returning that element wrapped in Some.
    • An array with multiple elements, recursively finding the largest element by comparing the first element with the largest of the rest.
  • Handle the Result: Use pattern matching to handle the result of the function, printing the largest element if it exists or a message indicating an empty array.
  • Display the Array Elements: Use a loop to print all elements of the array in a readable format.
  • Test with Different Arrays: Change the array values to verify the program works for various cases, including empty arrays, single-element arrays, and arrays with negative numbers.
  • Common Errors to Avoid:
    • Forgetting to handle the empty array case, leading to runtime errors.
    • Misplacing the comparison logic in the recursive function, causing incorrect results.
    • Not testing edge cases like arrays with duplicate elements or very small/large numbers, which may reveal unexpected behavior.

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.