Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the index of the maximum value in a List in Scala?

For a Scala List[Int] I can call the method max to find the maximum element value.

How can I find the index of the maximum element?

This is what I am doing now:

val max = list.max 
val index = list.indexOf(max)
like image 827
Phil Avatar asked Dec 23 '12 13:12

Phil


People also ask

How do you find the index of a max value in a list?

index() functions to find out the index of the maximum value in a list. Use the enumerate() function to find out the index of the maximum value in a list. Use the numpy. argmax() function of the NumPy library to find out the index of the maximum value in a list.

How do you use MAX function in Scala?

Scala Int max() method with exampleThe max() method is utilized to return the maximum value of the two specified int numbers. Return Type: It returns true the maximum value of the two specified int numbers.

What is the max index of an array?

max index(es) is the index for the first max value. If array is multidimensional, max index(es) is an array whose elements are the indexes for the first maximum value in array. min value is of the same data type and structure as the elements in array. min index(es) is the index for the first min value.


3 Answers

One way to do this is to zip the list with its indices, find the resulting pair with the largest first element, and return the second element of that pair:

scala> List(0, 43, 1, 34, 10).zipWithIndex.maxBy(_._1)._2 res0: Int = 1 

This isn't the most efficient way to solve the problem, but it's idiomatic and clear.

like image 176
Travis Brown Avatar answered Oct 11 '22 17:10

Travis Brown


Since Seq is a function in Scala, the following code works:

list.indices.maxBy(list) 
like image 45
Yuichiroh Avatar answered Oct 11 '22 17:10

Yuichiroh


even easier to read would be:

   val g = List(0, 43, 1, 34, 10)
   val g_index=g.indexOf(g.max)
like image 44
xhudik Avatar answered Oct 11 '22 15:10

xhudik