3

I want to create a matrix of size nxn where n is the length of input message:String. So far this is the only solution that came to my mind and that too has four for loops.

fun main(){
println("Enter the message:")
var message:String = readLine().toString()
var cipher = Array(message.length) { Array<Int>(message.length) {0} }
for(i in 0 .. (message.length - 1)){
    for(j in 0 .. (message.length - 1)){
        cipher[i][j] = readLine()!!.toInt()
    }
}
//print the matrix
for(i in 0..(message.length -1)){
    for(j in 0..(message.length -1)){
        print(cipher[i][j])
    }
    println()
   }
}

Is there any less complex code for the same? How can I improve this code?

EManual
  • 331
  • 4
  • 10

1 Answers1

7

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("") })
}
Salem
  • 13,516
  • 4
  • 51
  • 70