Мое решение является очень простой, но легко понять
/**
* 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
}
Это в значительной степени так же, как
/**
* 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
}
Возможный дубликат [Как могу ли я найти индекс максимального значения в списке в Scala?] (http://stackoverflow.com/questions/14011181/how-can-i-find-the-index-of-the-max imum-value-in-a-list-in-scala) – Suma