Pitos
Pitos

Reputation: 867

Console input String, output Array<Int> (Kotlin)

I'm trying to read a single line from the console, convert entered numbers to Integers, and add them to

Array<Int>

The shortest one-liner I came up with is

val na: Array<Int> = readLine()!!.split(' ').map{it.toInt()}.toTypedArray() // Array<Int>

This is much longer than e.g python version below. Is it possible to write a shorter code to achieve the same result? This would matter in the compativive programming.

na = [int(i) for i in input().split(' ')]

Upvotes: 0

Views: 773

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170825

Your Python version doesn't give you an array, it gives a list. Well, so does

val na = readLine()!!.split(' ').map{it.toInt()}

which is only longer then Python by a few characters.

Upvotes: 1

cd1
cd1

Reputation: 16534

You don't really need to declare the variable type, so:

val na = readLine()!!.split(' ').map { it.toInt() }.toTypedArray()

Does it have to be an array? Why can't you use a list? It'll probably be the same thing to you and you won't even notice the difference (if any at all). You'll be able to iterate over it the same way. For a list, you can have:

val na = readLine()!!.split(' ').map { it.toInt() }

I guess there's no way of making it shorter. readLine is longer than input, toInt is longer than int, and it is longer than i... there's not much more to do now. And it shouldn't matter, actually ;)

Upvotes: 3

Related Questions