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

2

8

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!

Colvert answered 2/1, 2019 at 1:12 Comment(1)
There is .min on just about anything that vaguely resembles a sequence of elements or a collection of some sort.Arteriole
P
15

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)
Ploce answered 2/1, 2019 at 1:24 Comment(0)
G
4

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
Gusher answered 2/1, 2019 at 4:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.