Rajeev Rajeev - 1 month ago 7
Scala Question

Find min and max elements of array

I want to find the min and max elements of an array using for comprehension. Is it possible to do that with one iteration of array to find both min element and max element?

I am looking for a solution without using scala provided array.min or max.

Answer Source

Here is a concise and readable solution, that avoids the ugly if statements :

def minMax(a: Array[Int]) : (Int, Int) = {
  if (a.isEmpty) throw new java.lang.UnsupportedOperationException("array is empty")
  a.foldLeft((a(0), a(0)))
  { case ((min, max), e) => (math.min(min, e), math.max(max, e))}
}

Explanation : foldLeft is a standard method in Scala on many collections. It allows to pass an accumulator to a callback function that will be called for each element of the array.

Take a look at scaladoc for further details