Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How to find the minimum of more than 2 elements?

Since the Math.min() function only allows for the use of 2 elements, I was wondering if there is maybe another function which can calculate the minimum of more than 2 elements.

Thanks in advance!

like image 594
Frederik Vanclooster Avatar asked Jan 02 '19 01:01

Frederik Vanclooster


2 Answers

If you have multiple elements you can just chain calls to the min method:

Math.min(x, Math.min(y, z))

Since scala adds the a min method to numbers via implicits you could write the following which looks much fancier:

x min y min z

If you have a list of values and want to find their minimum:

val someNumbers: List[Int] = ???
val minimum = someNumbers.min

Note that this throws an exception if the list is empty. From scala 2.13.x onwards, there will be a minOption method to handle such cases gracefully. For older versions you could use the reduceOption method as workaround:

someNumbers.reduceOption(_ min _)
someNumbers.reduceOption(Math.min)
like image 60
Aki Avatar answered Nov 12 '22 13:11

Aki


Add all numbers in the collection like the list and find a minimum of it.

scala> val list = List(2,3,7,1,9,4,5)
list: List[Int] = List(2, 3, 7, 1, 9, 4, 5)

scala> list.min
res0: Int = 1
like image 4
Mahesh Chand Avatar answered Nov 12 '22 13:11

Mahesh Chand