My solution is very simple but easy to understand
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
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 }
user4691169
source share