The index of the largest element in the array

Does anyone know how to get the index of the largest element from this function:

Scala programming language

def indexOfLargestElement(arr: Array[Int]): Int = 

For instance:

 indexOfLargestElement(Array( 1, -6, 4, 5, 2, -1) ) == 3 

I do not understand.-

Thank you for your help!

+4
source share
5 answers

Here's how to do it with one workaround:

 def indexOfLargest(array: Seq[Int]): Int = { val result = array.foldLeft(-1,Int.MinValue,0) { case ((maxIndex, maxValue, currentIndex), currentValue) => if(currentValue > maxValue) (currentIndex,currentValue,currentIndex+1) else (maxIndex,maxValue,currentIndex+1) } result._1 } 

This will use a tuple (maximum element index, known, maximum element value, curent index) to store data in a loop.

+10
source

val l = Array (1, -6, 4, 5, 2, -1)

l.indexOf (l.max)

+5
source
 scala> :paste // Entering paste mode (ctrl-D to finish) @annotation.tailrec final def indexOfLargestElement(a: Array[Int], i: Int = -1, mi: Int = -1, ma: Int = Int.MinValue): Int = { val i1 = i + 1 if (i1 < a.length) { val ai1 = a(i1) if (ai1 >= ma) indexOfLargestElement(a, i1, i1, ai1) else indexOfLargestElement(a, i1, mi, ma) } else mi } // Exiting paste mode, now interpreting. indexOfLargestElement: (a: Array[Int], i: Int, mi: Int, ma: Int)Int scala> indexOfLargestElement(Array(1, -6, 4, 5, 2, -1)) res0: Int = 3 scala> indexOfLargestElement(Array()) res1: Int = -1 scala> indexOfLargestElement(Array(Int.MinValue)) res2: Int = 0 
+5
source

I'm not sure what performance is because there can be expensive implicit conversions, and I cannot say which sorting algorithm is used in practice.

Nevertheless it is he

 scala> val arr = Array( 1, -6, 4, 5, 2, -1) arr: Array[Int] = Array(1, -6, 4, 5, 2, -1) scala> arr.zipWithIndex.maxBy(_._1)._2 res1: Int = 3 
+4
source

My solution is very simple but easy to understand

 /** * Returns the max index or -1 if there is no max index */ def getMaxIndex(array: Array[Int]): Int = { var maxIndex = -1 var max = Int.MinValue for { index <- 0 until array.length element <- array } { if (element > max) { max = element maxIndex = index } } maxIndex } 

It is almost the same as

 /** * Returns the max index or -1 if there is no max index */ def getMaxIndex(array: Seq[Int]): Int = { val startIndex = 0 val result = array.foldLeft(-1, Int.MinValue, startIndex) { case ((maxIndex, max, index), element) => { if(element > max) (index, element, index+1) else (maxIndex, max, index+1) } } result._1 } 
0
source

All Articles