## Kotlin Index of Maximum problem

January 28, 2012 § 3 Comments

On the Kotlin demo site there is some problems to solve. Here is my solution to the ‘Index of Maximum’ problem.

fun indexOfMax(a : IntArray) : Int? { if (a.size == 0) return null var max : Int = Integer.MIN_VALUE var maxPosition : Int = 0 for (i in a.indices) { if (a[i] >= max) { max = a[i] maxPosition = i } } return maxPosition }

I think Kotlin is an intresting attempt at a new language. Now I really would like to try it out in a real IDE.

Advertisements

fun indexOfMax(a: IntArray): Int? {

return a.indices.maxBy { a[it] } ?: null

}

It works with the first index but when there are 2 or more largest elements the last index must be returned instead.

This is my solution:

fun indexOfMax(a: IntArray): Int? {

return a.indices.maxWith(Comparator { o1, o2 -> a[o1].compareTo(a[o2]) – 1 })

}

This one should also work :

fun indexOfMax(a: IntArray): Int? {

return a.withIndex().reversed().maxBy { it.value }?.index

}