Home > Back-end >  how to print a multidimension array in kotlin?
how to print a multidimension array in kotlin?

Time:09-15

i'm new to kotlin and need help printing this problem below

how do you print this code:

val chessBoard = mutableListOf(
        mutableListOf<String>(" ", "a", "b", "c", "d", "e", "f", "g", "h"),
        mutableListOf<String>("1", " ", " ", " ", " ", " ", " ", " ", " "),
        mutableListOf<String>("2", "W", "W", "W", "W", "W", "W", "W", "W"),
        mutableListOf<String>("3", " ", " ", " ", " ", " ", " ", " ", " "),
        mutableListOf<String>("4", " ", " ", " ", " ", " ", " ", " ", " "),
        mutableListOf<String>("5", " ", " ", " ", " ", " ", " ", " ", " "),
        mutableListOf<String>("6", " ", " ", " ", " ", " ", " ", " ", " "),
        mutableListOf<String>("7", "B", "B", "B", "B", "B", "B", "B", "B"),
        mutableListOf<String>("8", " ", " ", " ", " ", " ", " ", " ", " "),
    )

into this:

   --- --- --- --- --- --- --- --- 
8 |   |   |   |   |   |   |   |   |
   --- --- --- --- --- --- --- --- 
7 | B | B | B | B | B | B | B | B |
   --- --- --- --- --- --- --- --- 
6 |   |   |   |   |   |   |   |   |
   --- --- --- --- --- --- --- --- 
5 |   |   |   |   |   |   |   |   |
   --- --- --- --- --- --- --- --- 
4 |   |   |   |   |   |   |   |   |
   --- --- --- --- --- --- --- --- 
3 |   |   |   |   |   |   |   |   |
   --- --- --- --- --- --- --- --- 
2 | W | W | W | W | W | W | W | W |
   --- --- --- --- --- --- --- --- 
1 |   |   |   |   |   |   |   |   |
   --- --- --- --- --- --- --- --- 
    a   b   c   d   e   f   g   h

thanks for helping out

CodePudding user response:

joinToString() is your friend:

val line = "\n    --- --- --- --- --- --- --- --- \n"
chessBoard.reversed().joinToString(separator = line, prefix = line) { l ->
    l.joinToString(separator = "|", postfix = "|") { " $it " }
}.also{println(it)}

CodePudding user response:

This could do it:

println(
    ((chessBoard)
        .reversed()
        .map { (it   "").joinToString(if (it[0] != " ") " | " else "   ")   "\n" })
        .run { arrayOf("")   this }
        .joinToString("   --- --- --- --- --- --- --- --- \n")
)
  • Related