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.
int min = array[0]; This statement is executed at a time when array[0] is zero. You have not read any values at this point, so initialize your min and max values with: int max = Integer.
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
You can get min and max values of an Array[Int] with reduceLeft
function.
scala> val a = Array(20, 12, 6, 15, 2, 9)
a: Array[Int] = Array(20, 12, 6, 15, 2, 9)
scala> a.reduceLeft(_ min _)
res: Int = 2
scala> a.reduceLeft(_ max _)
res: Int = 20
See this link for more information and examples of reduceLeft
method: http://alvinalexander.com/scala/scala-reduceleft-examples
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With