Overview and Goal

Hey, welcome on board! Today's exciting journey explores multidimensional arrays in Kotlin, which are much like a chessboard in the world of programming. Our aim is to empower you to create, access, and modify these versatile arrays. So buckle up and let's get started!

Visualizing a Multidimensional Array

Imagine a multidimensional array as an array of arrays. It operates like a chessboard; each square, which can be identified by its row and column coordinates, represents a specific value or chess piece. Note that this 2D visualization doesn't limit us. Kotlin allows us to create arrays with 3, 4, or even more dimensions, naturally extending this concept.

Creating a Multidimensional Array

Kotlin provides the arrayOf() function for declaring multidimensional arrays. Here's how it works:

fun main() {
    val chessboard = arrayOf(   // Start of the outer array
        arrayOf("R", "N", "B", "Q", "K", "B", "N", "R"),   // Each inner array represents a row on the chessboard
        arrayOf("P", "P", "P", "P", "P", "P", "P", "P"),
        arrayOf("", "", "", "", "", "", "", ""),
        // ...
    )   // End of the outer array

    // Access and print first two rows of the chessboard
    println("Row 1: ${chessboard[0].joinToString()}")  // Outputs: Row 1: R, N, B, Q, K, B, N, R
    println("Row 2: ${chessboard[1].joinToString()}")  // Outputs: Row 2: P, P, P, P, P, P, P, P
}

In our chessboard array abstraction, each row represents an inner array, the elements of which we can access using two indices.

Accessing Elements in a Multidimensional Array

Let's use our chessboard analogy to retrieve a piece from a particular location:

fun main() {
    val chessboard = arrayOf( 
        arrayOf("R", "N", "B", "Q", "K", "B", "N", "R"),
        arrayOf("P", "P", "P", "P", "P", "P", "P", "P"),
        arrayOf("", "", "", "", "", "", "", ""),
        // ...
    )

    val piece = chessboard[0][2]   // Access 3rd piece at the first row
    println(piece)   // Outputs: B
}

In the above example, piece holds "B" (representing a bishop in chess) at coordinates (0, 2) because, like most languages, Kotlin uses zero-indexed arrays.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal