Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find min and max elements of array

Tags:

scala

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.

like image 718
Rajeev Avatar asked Nov 29 '13 11:11

Rajeev


People also ask

How do you find the max and min of an array in Java?

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.

How do you find the maximum element of an array?

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.


2 Answers

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

like image 149
Henri Hietala Avatar answered Oct 02 '22 12:10

Henri Hietala


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

like image 21
Yann Moisan Avatar answered Oct 02 '22 13:10

Yann Moisan