Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple ints from the same line in Kotlin?

Tags:

kotlin

I am doing the 30 Days of Code in Kotlin on Hackerrank and I am stuck at Day 7.

How do you read multiple integers on a single line?

How is it added to an array and displayed in reverse?

I have solved it in Java but lack the syntax needed in Kotlin

Input:

4

1 4 3 2

My Code:

fun main(args: Array<String>) {

   val n = readLine()!!.toInt()
   var arr = Array(n)
   for(i in 0 until n)
   {
      arr[i] = readLine()!!.toInt() //Not Working? nor does readLine()!!.split(' ').toInt()

   }
   for(item in arr.size - 1 downTo 0)
   {
      print("${item} ")
   }
}
like image 391
Tadhg Deeney Avatar asked Oct 25 '25 07:10

Tadhg Deeney


1 Answers

EDIT: question was updated from the original

The problem is the readLine() will read the entire line from stdin, so each time you call readLine() in the for loop it will result in a separate line being read each time.

One approach to this is to read the line, and then to split and map each value to an Int.

readLine()?.let {
    val numOfValues = it.toInt()
    println(numOfValues)

    readLine()?.let { line ->
        line.split(" ").map {
            it.toInt()
        }.reversed().forEach {
            println(it)
        }
    }
}
like image 168
JK Ly Avatar answered Oct 28 '25 03:10

JK Ly