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

Tagged:

§ 3 Responses to Kotlin Index of Maximum problem

  • yang zhang says:

    fun indexOfMax(a: IntArray): Int? {
    return a.indices.maxBy { a[it] } ?: null
    }

    • Hugo Angeles says:

      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 })
      }

      • LeGo says:

        This one should also work :

        fun indexOfMax(a: IntArray): Int? {
        return a.withIndex().reversed().maxBy { it.value }?.index
        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Kotlin Index of Maximum problem at Strange Epiphany.

meta

%d bloggers like this: