Assuming your input data is row-major, this can be simplified by moving the array filling logic into the array creation itself:
var cipher = Array(message.length) {
IntArray(message.length) { readLine()!!.toInt() }
}
Array
's constructor takes an initializer function that is invoked size
times to populate the array. By reading user input here, you can populate the array while the matrix is being created and avoid having to write an extra loop.
Miscellaneous notes:
readLine().toString()
is redundant and possibly harmful. readLine
returns a String?
, and you invoke Any?.toString
on it, which either returns the result of Any.toString
if its receiver is not null, or the literal string "null"
(which is probably not desired.)
- Consider using the
until
infix function when looping over arrays (0 until length
), rather than 0..(length - 1)
(or, even better, the Array.indices
extension property.)
- Consider using the corresponding primitive array type (i.e.
IntArray
, FloatArray
, etc. rather than Array<*>
)
See also:
You can also avoid your output loop entirely by simplifying your code:
println(cipher.joinToString("\n") { row -> row.joinToString("") })
Here's a simpler piece of code:
fun main() {
println("Enter the message:")
var message = readLine()!!
var cipher = Array(message.length) {
IntArray(message.length) { readLine()!!.toInt() }
}
println(cipher.joinToString("\n") { it.joinToString("") })
}