How to convert a matrix of numbers to a string in Kotlin

1 Answer

0 votes
fun matrixToString(matrix: Array<IntArray>): String {
    return matrix.joinToString(separator = "\n") { row ->
        row.joinToString(separator = " ") { it.toString() }
    }
}

fun main() {
    val matrix = arrayOf(
    	intArrayOf(4, 7, 9, 18, 29, 0),
  		intArrayOf(1, 9, 18, 99, 4, 3),
  		intArrayOf(9, 17, 89, 2, 7, 5),
  		intArrayOf(19, 49, 6, 1, 9, 8),
  		intArrayOf(29, 4, 7, 9, 18, 6)
    )
    
    val result = matrixToString(matrix)
    
    println(result)
}


 
/*
run:
 
4 7 9 18 29 0
1 9 18 99 4 3
9 17 89 2 7 5
19 49 6 1 9 8
29 4 7 9 18 6
 
*/

 



answered May 24 by avibootz
...