Thuy's Blog

HackerRank supports Kotlin

June 02, 2017

Last year, I once wished HackerRank would support Kotlin. Today, when I gave their HourRank 21 a shot, I was surprised that Kotlin appeared on their language stack. And the supported version is the latest, 1.1.2, so far. After the contest, I managed to solve only the easiest problem (Who Gets the Catch?). Here comes my submission. The code may not be so optimal as I didn’t pay much attention to performance during the short time limit. I’m really into how Kotlin deals with standard input and standard output.

fun main(args: Array<String>) {
  fun readLineAsInts(): List<Int>
      = readLine().toString().split(" ").map { it.toInt() }

  val firstLine = readLineAsInts()
  val catcherCount = firstLine[0]
  val venotoisePosition = firstLine[1]
  val catcherPositions = readLineAsInts()
  val catcherVelocities = readLineAsInts()
  val times = catcherPositions
      .map { Math.abs(it - venotoisePosition) }
      .mapIndexed {
        index, e ->
        Pair(index, e.toDouble() / catcherVelocities[index])
      }
      .sortedBy { it.second }
  if (catcherCount > 1 && (times[0].second == times[1].second))
    println(-1)
  else
    println(times[0].first)
}

Let me know if you can come up with a more optimal and intuitive solution.


Thuy Trinh

Written by Thuy Trinh who lives and works in Frankfurt, Germany building robust Android apps. You should follow him on Twitter